Home > database >  std::function template with multiple template parameters
std::function template with multiple template parameters

Time:09-16

When looking for documentation on std::function, I found several pages, that list two implementations of std::function for C 11:

template< class >
class function; /* undefined */
template< class R, class... Args >
class function<R(Args...)>;
template <class T> function;     // undefined
template <class Ret, class... Args> class function<Ret(Args...)>;
template<class >
class function;

and

template< class R, class... Args >
class function<R(Args...)>

I tried to use the multi-parameter version of the function<>-template, but my code does not compile, neither with visual c 2017, nor with XCode or g . Here is my sample code:

#include <functional>

int main(int argc, char*argv[])
{
        std::function<void, int> cb;
}

All compilers complain on std::function taking only a single template parameter.

Can anybody explain this?

CodePudding user response:

The template argument list of std::function has a single type, as seen in the base template:

template <class>
class function;

What you see in the following:

template <class ReturnType, class... Arguments>
class function<ReturnType(Arguments...)> 
{
  ...
};

is a partial specialization, where the types mentioned are used for pattern matching. Essentially the specialization says:

"The type of std::function, that single type mentioned in the base template, is a callable type with such a ReturnType and such ArgumentTypes

CodePudding user response:

that list two implementations of std::function for C 11:

No they don't. That isn't what they're showing at all.

template< class >
class function; /* undefined */

is the base template, which (as it says), is never defined.

For example, std::function<int> would never make sense, so there is simply no template defined that could match that pattern.

template< class R, class... Args >
class function<R(Args...)>;

is a partial specialization.

That is, std::function<T> is only defined at all when T has the form R(Args...), meaning T is the type of a function returning R and taking the arguments Args....

Hence your attempt should be std::function<void(int)> cb; ... exactly as shown in the extensive examples at the bottom of the cppreference page you linked.

  • Related