How to Check if the function exists in C/C++

前端 未结 8 2062
失恋的感觉
失恋的感觉 2020-12-01 06:24

Certain situations in my code, i end up invoking the function only if that function is defined, or else i should not. How can i achieve this ?

like:
if (func         


        
8条回答
  •  借酒劲吻你
    2020-12-01 06:56

    So another way, if you're using c++11 would be to use functors:

    You'll need to put this at the start of your file:

    #include 
    

    The type of a functor is declared in this format:

    std::function< return_type (param1_type, param2_type) >
    

    You could add a variable that holds a functor for sum like this:

    std::function&)> sum;
    

    To make things easy, let shorten the param type:

    using Numbers = const std::vectorn&;
    

    Then you could fill in the functor var with any one of:

    A lambda:

    sum = [](Numbers x) { return std::accumulate(x.cbegin(), x.cend(), 0); } // std::accumulate comes from #include 
    

    A function pointer:

    int myFunc(Numbers nums) {
        int result = 0;
        for (int i : nums)
            result += i;
        return result;
    }
    sum = &myFunc;
    

    Something that 'bind' has created:

    struct Adder {
        int startNumber = 6;
        int doAdding(Numbers nums) {
            int result = 0;
            for (int i : nums)
                result += i;
            return result;
        }
    };
    ...
    Adder myAdder{2}; // Make an adder that starts at two
    sum = std::bind(&Adder::doAdding, myAdder);
    

    Then finally to use it, it's a simple if statement:

    if (sum)
        return sum(x);
    

    In summary, functors are the new pointer to a function, however they're more versatile. May actually be inlined if the compiler is sure enough, but generally are the same as a function pointer.

    When combined with std::bind and lambda's they're quite superior to old style C function pointers.

    But remember they work in c++11 and above environments. (Not in C or C++03).

提交回复
热议问题