In the "C + + template" has a type of identification function templates technology, the original example seems to be some errors, here to do a comparison to verify, if there are errors, please point out that the original code is as follows:
Template<typename T>class Compoundt {public:enum {isptrt = 0, Isreft = 0, Isarrayt = 0, isfunct = 0, IsPtrMemT = 0 };typedef t baset;typedef t bottomt;typedef compoundt<void> classt;};
This is the basic template, and then you need to define a basic template that identifies the function type:
Template<typename t>class compoundt<t () > {public:enum {isptrt = 0, Isreft = 0, Isarrayt = 0, IsFuncT = 1, IsP TRMEMT = 0};typedef t BaseT (); typedef t BOTTOMT (); typedef compoundt<void> CLASST;};
This special class template can recognize the function type without parameters, for the purpose of flexible use, the original text through a template function to complete the specific recognition work, as follows:
Template<typename t>void Test (t) {Cout<<typeid (t). Name () <<endl;cout<< (COMPOUNDT<T>: : isfunct) <<endl;}
Whether this template function works or not, we can verify it on the ground:
void Fun () {}int main () {test (fun); return 0;}
The results of the discovery output are as follows:
typeID (T). Name (): Pfvve
Compoundt<t>:: isfunct:0
Obviously, the result of recognition is wrong, the problem is in the definition of test, notice the parameter list of test (T), that is, the use of the value of the method, and if the pass is a function, will occur decay, the function name decay is a function pointer, so T is inferred as the function pointer type, Instead of the function type, the specific version defined above cannot match it. Now redefine test as follows: (Change T to t&)
Template<typename t>void Test (t&) {Cout<<typeid (T). Name () <<endl;cout<< (compoundt<t >::isfunct) <<endl;}
Perform the same test again, with the following results:
typeID (T). Name (): Fvve
Compoundt<t>:: isfunct:1
Visible, so that the function type can be correctly identified. In addition, we can see the great advantage of using template functions in conjunction with template classes, because template functions can perform type inference (type deduction). Without the use of function templates, Compoundt's role is greatly reduced because it cannot be written as Compoundt<fun> because fun is not a type, fun is equivalent to an instance of a type. To illustrate this more concretely, we can define the following:
typedef void Func ();
This makes it possible to use compoundt<func>, because Func is now a function type.
C + + templates: Distinguishing function types