【发布时间】:2020-10-15 09:23:40
【问题描述】:
我想通过 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'。
有没有办法解决这个问题?
提前感谢您! :)
【问题讨论】:
-
gcc 和 clang 之间关于受保护的析构函数的行为有一个有趣的差异:godbolt.org/z/W6M8Mo 也许你想问另一个问题(我也会感兴趣) - 编辑:啊,那是仅在 C++20 中但不在 C++11 模式下 oO
标签: c++ c++11 crtp perfect-forwarding static-polymorphism