Here is base class:
class Product
{
public:
static void RegisterClass() {
string b = __FUNCTION__;
};
}
and here is the derived class.
class Milk: Product
{}
in the main function I call the static method this way:
main(){
Milk.RegisterClass();
}
Then it writes value Product::RegisterClass
into variable b
. Is there a way to get value Milk::RegisterClass
in the static method.
I don't want to instantiate the classes. And the main goal behind this scenario is to register Milk
string somewhere.
CodePudding user response:
The fairly constrained scenario presented by OP can be achieved reasonably well with the use of CRTP:
As pointed out in the comments, type_info::name()
is fraught with uncertainty, so a better approach would be to explicitly state the string to use:
#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();
}