基类中的静态方法反映了派生类的名称

Ary*_*ian 1 c++ reflection inheritance static-methods

这是基类:

class Product
{
public:
    static void RegisterClass() {
        string b = __FUNCTION__;
    };
}
Run Code Online (Sandbox Code Playgroud)

这是派生类。

class Milk: Product
{}
Run Code Online (Sandbox Code Playgroud)

在主函数中我这样调用静态方法:

main(){
    Milk.RegisterClass();
}
Run Code Online (Sandbox Code Playgroud)

然后写入值Product::RegisterClass变量bMilk::RegisterClass有没有办法在静态方法中获取值。

我不想实例化这些类。这个场景背后的主要目标是在某处注册Milk字符串。

小智 5

使用 CRTP 可以很好地实现 OP 提出的相当受限的场景。

正如评论中指出的,type_info::name()充满了不确定性,因此更好的方法是明确声明要使用的字符串:

#include <string>
#include <string_view>
#include <iostream>

template<typename CRTP>
class Product
{
public:
    static void RegisterClass() {
        std::string b{CRTP::product_name};
        std::cout << b << "\n";
    };
};

class Milk : public Product<Milk> {
public:
    static constexpr std::string_view product_name{"Milk"};
};

int main() {
    Milk::RegisterClass();
}
Run Code Online (Sandbox Code Playgroud)