Converting a template parameter to a custom template type to set template parameters

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

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 if this works, I'm not sure what this code does. Why does this code work and does it comply with the C ++ standard?

+6
c ++ templates
source share
3 answers

Why should this not work? This instance corresponds to a specialization that retrieves component types ( char and int ) of a composite type ( char(int) function) like Type1 and Type2 .

By the way, you do not have a non-type template parameter. Type of function - type. If you have a non-type template parameter, it will look like this:

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

Or completely the template:

 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 } 
+7
source share

This question is incorrect, because FuncSignature not a parameter of the non-piggy type template.

However, the code above works by specializing in the (generic) FuncSignature type for unary function types ( Type1 (Type2) is the type of function specified by Types Type1 and Type2 ).

So, the first line defines the general template, the next group of lines specializes in the type Type1 (Type2) , which are parameterized on two types, therefore specialization has a list of parameters of a non-empty template, and main creates a template for a particular type char (int) (the function accepts int and returns a char ).

+3
source share

Yes. This code is standard :)

When:

 Obj<char (int)> 

Type1 is char , and Type2 is int . For this reason, Obj::var1 is a member variable of type char and Obj::var2 is a member variable of type int .

0
source share

All Articles