Home > Mobile >  is it possible to create a new variable from a user-defined data type by "using" keyword?
is it possible to create a new variable from a user-defined data type by "using" keyword?

Time:06-26

I have the following:

class EventHandler {
    template <class T>
    using Handler = void(T::*)(Object* sender) ;
    template <class T>
    Handler<T> m_Handler;  // <===
public:
    template <class T>
    EventHandler(Handler<T> handler) : m_Handler(handler) {}
    // ....
   // ...
};

But this line Handler<T> m_Handler; occurs an error:
error C3376: EventHandler::m_Handler: only static data member templates are allowed.

Is that mean that the "using" keyword can't create a user-defined datatype like "typedef"?

CodePudding user response:

This has nothing to do with the using keyword, whatsoever. The problematic declaration is:

template <class T> Handler<T> m_Handler;

It is immaterial where Handler came from.

This is attempting to declare a non-function class member named m_Handler ...that's a template. There's no such thing in C . All class members must be specific, concrete types and not templates. You could declare a class member that's a template:

template<class T> class Handler {

  //...
};

That would be a member of this class. And then you can declare some specific instance of this template, as a class member:

Handler<int> m_Handler

But the shown code attempts to declare something that's both a template and some data member of the class. Something like this does not exist in C .

CodePudding user response:

If the class must hold a Handler<T> then the class must be templated:

template<class T>
class EventHandler {
    using Handler = void(T::*)(Object* sender);
    Handler<T> m_Handler;
public:
    EventHandler(Handler<T> handler) : m_Handler(handler) {}
    // ....
   // ...
};
  • Related