Search code examples
templatesc++11syntaxvariadic-templatesstd-function

C++ std::function-like template syntax


In C++11 you can instantiate std::function like this:

std::function<void(int)> f1;
std::function<int(std::string, std::string)> f2;
//and so on

But while there is plenty of info on variadic templates on the web, I fail to find any articles on how to write std::function-like template which would accept parenthesized arguments. Could anyone please explain the syntax and its limitations or at least point to an existing explanation?


Solution

  • There's nothing special about it, it's an ordinary function type. When you declare a function like this:

    int foo(char a, double b)
    

    Then its type is int (char, double). One way of "unwrapping" the individual argument types and return type is to use partial template specialisation. Basically, std::function looks something like this:

    template <class T>
    struct function; // not defined
    
    template <class R, class... A>
    struct function<R (A...)>
    {
      // definition here
    };