Passing any function as template parameter

前端 未结 3 1704
天涯浪人
天涯浪人 2021-01-31 03:10

I want to pass a function value as a template parameter to a function. Currently the best I managed to do is :

template< typename F, F f >         


        
3条回答
  •  孤城傲影
    2021-01-31 03:27

    It's now possible in C++17 with template:

    template
    struct FuncWrapper final
    {
        template
        auto operator()(Args &&... args) const
        {
            return Func(std::forward(args)...);
        }
    };
    
    int add(int a, int b)
    {
        return a + b;
    }
    
    int main()
    {
        FuncWrapper wrapper;
        return wrapper(12, 34);
    }
    

    Demo: https://godbolt.org/g/B7W56t

    You can use #ifdef __cpp_nontype_template_parameter_auto to detect compiler support for this in your code.

    If you are able to use C++20 and you want better error messages, you can also use concepts:

    template
    concept CanAddTwoNumbers = std::is_invocable_r_v;
    
    template
        requires CanAddTwoNumbers
    struct AddTwoNumbersWrapper final
    {
        auto operator()(int a, int b) const
        -> int
        {
            return std::invoke(Func, a, b);
        }
    };
    
    int add(int a, int b)
    {
        return a + b;
    }
    
    int main()
    {
        AddTwoNumbersWrapper wrapper;
        return wrapper(12, 34);
        AddTwoNumbersWrapper<123> bad; //error: constraint failure
    }
    

    Demo: https://gcc.godbolt.org/z/ai3WGH

提交回复
热议问题