C++ unique static id and class name with base class

前端 未结 3 1823
再見小時候
再見小時候 2021-01-22 20:32

Having class TaskBase, each derived class of it must have name and unique id.

The TaskBase is something like below:

class TaskB         


        
3条回答
  •  后悔当初
    2021-01-22 21:08

    class TaskBase
    {
    private:
        const void*  m_id;
        string m_name;
    
    public:
        TaskBase(const void* m_id, string m_name): m_id(m_id), m_name(m_name)
        {
        }
    
        const void* id() const
        {
            return m_id;
        }
    
        string name() const
        {
             return m_name;
        };
    };
    
    template< typename DERIVED >
    class TaskProxy: public TaskBase
    {
    public:   
        static const void* id()
        {
            //if you want to have for each object a unique id:
            //return reinterpret_cast(this);
            //just for each TaskProxy:
            return reinterpret_cast(typeid( DERIVED ).name());
        }
    
        static string name()
        {
            return typeid( DERIVED ).name();
        }
    
        TaskProxy(): TaskBase(id(), name()) {}
    };
    

    Usage:

    class MyTask1 : public TaskProxy< MyTask1 >
    {
    };
    
    class MyTask2 : public TaskProxy< MyTask2 >
    {
    };
    
    ...
    
    MyTask1 myTask1;
    TaskBase *baseA = &myTask1;
    MyTask2 myTask2;
    TaskBase *baseB = &myTask2;
    
    cout << "Name: " << baseA->name() << "  Id:" << baseA->id() << endl;
    cout << "Name: " << baseB->name() << "  Id:" << baseB->id() << endl;
    

    Which outputs this (with gcc 4.6):

    Name: 7MyTask1  Id:0x401228
    Name: 7MyTask2  Id:0x4011c0
    

提交回复
热议问题