A member of the pointer function inside the template class gives an error: there must be a class or namespace followed by '::'

I am trying to declare a template function pointer in C ++.

template <class T> class MyClass { public: typedef const unsigned char* (T::*MyTemplatedEvent)(unsigned long &myParameter); }; 

but for some reason, I get this error all the time:

'T': there must be a class or namespace followed by '::'

Can someone tell me what I'm doing wrong?
the compiler should know that T is a class. He says so above the MyClass announcement ...

+6
source share
5 answers

I guess this is because I'm trying to create a "MyClass" template, which is a pointer or primitive that, as the compiler knows, cannot have a function pointer associated with it ...

+1
source

With T::*MyTemplatedEvent you expect T be a class type, since only class types can have pointers to elements. This means that if you pass a non-classical type, say int or char* , you will get the specified error, since there are no such elements and, conversely, there are no member pointers for these types.

the compiler should know that T is a class. He says so above the MyClass announcement ...

Wrong. class T matches typename T in the template parameter and tells the compiler that T is a placeholder for any type that is later passed as the template argument. It does not limit the type of the class type.

+2
source

First of all, note that in the definition of MyClass in two ways, two declare the class as

 template< class T > class MyClass 

and

 template< typename T > class MyClass 

equivalent, you do not give the compiler more information using one keyword compared to another.

In addition, I would say that the compiler is right, MyClass <int> will not work, because you cannot write int :: something in C ++, whereas, for example, MyClass <std :: string> will work fine.

0
source

Try the following:

 typedef T type; typedef const unsigned char* (type::*MyTemplatedEvent)(unsigned long &myParameter); 
-1
source

I don’t think you can have a pointer to a template function in C ++, you can check this C ++ link , a pointer to a pointer to a template function

"typedef const unsigned char * (T :: * MyTemplatedEvent) (unsigned long & myParameter);" here T is a template parameter, not a namespace or class type, T is a data type that can be defined by the user or basic data types such as int or char, but it is not a namespace or class, so therefore you get a compilation error, which is correct.

-1
source

Source: https://habr.com/ru/post/917247/


All Articles