這里是基類:
class Product
{
public:
static void RegisterClass() {
string b = __FUNCTION__;
};
而這里是派生類。
class Milk: 產品
{}
在主函式中,我是這樣呼叫靜態方法的:
main(){
Milk.RegisterClass()。
}
然后它把值Product::RegisterClass寫到變數b。有沒有辦法在靜態方法中獲得Milk::RegisterClass的值呢?
我不想實體化這些類。而這個場景背后的主要目標是在某個地方注冊Milk字串。
uj5u.com熱心網友回復:
通過使用CRTP,可以合理地實作OP所提出的相當受限的場景:
正如所指出的那樣,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 << "
"。
};
};
class Milk : public Product< Milk> {
public:
static constexpr std::string_view product_name{"milk"}。
};
int main() {
Milk::RegisterClass()。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/306734.html
標籤:
