#include <iostream>
#include <string>
template<typename T>
class animal
{
public:
std::string print()
{
return static_cast<T*>(this)->impl_print();
};
protected:
inline const static std::string verb = "says ";
};
template<typename T>
class pet : public animal<pet<T>>
{
public:
std::string impl_print()
{
return verb + static_cast<T*>(this)->impl_print();
};
inline const static std::string excite = "!";
};
class cat : public pet<cat>
{
public:
std::string impl_print()
{
return "meow" + excite;
};
};
class dog : public pet<dog>
{
public:
std::string impl_print()
{
return "WOOF" + excite;
};
};
int main()
{
cat a;
dog c;
std::cout<<a.print()<<std::endl;
std::cout<<c.print()<<std::endl;
return 0;
}
这会出现“'verb' 未在此范围内声明”错误。 为什么CRTP链末端的类可以访问父类声明的变量,而中间类却不能访问自己父类声明的变量?
使用 gcc13 进行测试。
因为它的父级依赖于模板参数。目前尚不清楚动词的含义 - 全局变量或类成员,该模板中并未正式声明。可以对
animal
进行专门化,可以以不同的方式定义 verb
. Using
this->` 将修复它。
std::string impl_print()
{
return this->verb + static_cast<T*>(this)->impl_print();
};