1

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?

3
  • 1
    void, int doesn't look compatible with R(Args...). R - return type. Args... - pack of arguments. Specify it as void(int) Commented Sep 15, 2022 at 13:44
  • You basically want to specify the template type as ReturnType(Arg1Type, Arg2Type...). E.g.: godbolt.org/z/s4xoveqsE Commented Sep 15, 2022 at 14:05
  • typo: std::function<void(int)> cb; Commented Sep 15, 2022 at 15:13

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.