C++ “Object” class

扶醉桌前 提交于 2019-12-03 05:53:10

There's no generic base class in C++, no.

You can implement your own and derive your classes from it, but you have to keep collections of pointers (or smart pointers) to take advantage of polymorphism.

EDIT: After re-analyzing your question, I have to point out std::list.

If you want a list which you can specialize on multiple types, you use templates (and std::list is a template):

std::list<classA> a;
std::list<classB> b;

If you want a list which can hold different types in a single instance, you take the base class approach:

std::list<Base*> x;
MuffinMan
class Object{
protected:
    void * Value;
public:



template <class Type>
void operator = (Type Value){
        this->Value = (void*)Value;
}

template <>
void operator = <string>(string Value){
        this->Value = (void*)Value.c_str();
}

template <class Type>
bool operator ==  (Type Value2){
        return (int)(void*)Value2==(int)(void*)this->Value;
}

template<>
bool operator == <Object> (Object Value2){
        return Value2.Value==this->Value;
}

template <class ReturnType>
ReturnType Get(){
    return (ReturnType)this->Value;
}

template <>
string Get(){
    string str = (const char*)this->Value;
    return str;
}

template <>
void* Get(){

    return this->Value;
}

void Print(){
    cout << (signed)this->Value << endl;
}


};

Then make a subclass of it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!