Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the obscure template parameter of std::function

Tags:

c++

c++11

The std::function has a template parameter:

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

I am wondering, what type R(Args...) is, I think it is neither a function pointer T:

template<class R, typename... Args>
using T = R(*)(Args...);

nor a function reference Q:

template<class R, typename... Args>
using Q = R(&)(Args...);

So the type P

template<class R, typename... Args>
using P = R(Args...);

is simply a function.

And I can declare such a function and call it by:

int main(){
  P<int,int> myFunc;
  myFunc(3);
}

which will not compile since myFunc has never been defined. If that is correct, where can I find more information about this type function in the standard?

like image 421
Gabriel Avatar asked Jul 07 '18 12:07

Gabriel


1 Answers

As you've noted, the type is just a function type, which is a perfectly well-defined type in the C++ type system, defined in section 3.9.2 of the spec:

3.9.2 Compound types

— functions, which have parameters of given types and return void or references or objects of a given type

The program:

template<class R, typename... Args>
using P = R(Args...);

int main(){
  P<int,int> myFunc;
  myFunc(3);
}

will compile just fine. What it won't do is link -- you'll get an error like

prog.cpp:6: undefined reference to `myFunc(int)'

due to the fact that you've declared a function (and called it), but never defined it.

like image 124
Chris Dodd Avatar answered Oct 20 '22 15:10

Chris Dodd