使用静态方法进行C++设计

use*_*536 5 c++ static

我想用静态方法定义为类X:

class X
{
 static string get_type () {return "X";}
 //other virtual methods
}
Run Code Online (Sandbox Code Playgroud)

我想强制继承自X的类重新定义get_type()方法并返回与"X"不同的字符串(如果他们现在只重新定义get_type,我很高兴).

我该怎么做呢?我知道我不能拥有虚拟静态方法.

编辑:问题不是关于type_id,而是关于应该重写的静态方法.例如

class X {
 static int getid() {return 1;}
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*som 5

template<int id>
class X {
public:
    static int getid() { return id; }
};

class Y : public X<2> {
};
Run Code Online (Sandbox Code Playgroud)

您没有覆盖该方法,但您已强制每个子类提供ID.警告:我没有试过这个,可能有一些微妙的原因导致它不起作用.


pmr*_*pmr 1

不要这样做,typeid而是使用。