我想通过 CRTP 使用“静态多态性”来执行以下操作:
template <typename T>
struct Base
{
double get_value() const { return ((T*)this)->_get_value(); }
protected:
~Base() {}
};
struct Derived1 : public Base<Derived1>
{
double value;
Derived1() : value(3.) {}
const double& _get_value() const { return value; }
};
struct Derived2 : public Base<Derived2>
{
double _get_value() const { return 5.; }
};
这可行,但我也希望在对象被实例化为的情况下Derived1
,get_value
返回对值的 const 引用而不是返回副本。所以在某种程度上,是一种返回值的“完美转发”。
我试图get_value
像这样声明 的返回类型:
template <typename T>
struct Base
{
decltype(std::declval<T>()._get_value()) get_value() const { return ((T*)this)->_get_value(); }
...
但不出所料,GCC 抱怨这是一个invalid use of incomplete type 'struct Derived1'
.
有什么办法可以解决这个问题吗?
先感谢您!:)