Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of Function Pointer Non-Type Template Parameter to Type Template Parameters

Tags:

c++

templates

The following example code compiles under gcc and works as I would hope. It allows me to instantiate an object with a function definition as a template parameter, but then the class is able to use the different types in the function as if they were passed individually as type template parameters.

template<class FuncSignature> class Obj;

template<class Type1, class Type2> class Obj<Type1 (Type2)>
{
public:
  Type1 var1;
  Type2 var2;
};

int main(int argc, char **argv)
{
  Obj<char (int)> A;
  A.var1 = 'a';
  A.var2 = 3;
}

Even though it seems to work, I'm not sure what this code is doing. Why does this code work and does it conform to the C++ standard?

like image 344
user334066 Avatar asked Nov 28 '10 15:11

user334066


1 Answers

Why shouldn't it work? The instantiation matches the specialization, which extracts the component types (char and int) of the compound type (a function, char(int)) as Type1 and Type2.

By the way, you don't have a non-type template parameter. A function type is a type. If you had a non-type template parameter, then it would look like this:

template <char(int)>
struct X {};

char foobar(int);

int main()
{
    X<foobar> x;
}

Or fully templated:

template <class R, class A, R(A)>
//                          ^^^^
//                      non-type parameter
struct X {};

char foobar(int);

int main()
{
    X<char, int, foobar> x;
//               ^^^^^^
//   a specific function, not type
}
like image 80
UncleBens Avatar answered Nov 10 '22 00:11

UncleBens