gpt4 book ai didi

c++ - CRTP派生类方法返回类型的转发

转载 作者:行者123 更新时间:2023-12-03 07:00:33 25 4
gpt4 key购买 nike

我想通过 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 拒绝 OP 中提出的解决方案的原因是 Base<Derived1>正在被实例化 Derived1 .这种实例化包括所有成员函数签名的实例化,但它不实例化函数体本身。
所以我们需要将成员函数的签名/返回类型的确定推迟到Derived1之后。是可见的。
一种方法是通过 decltype(auto) 推迟确定返回类型。 .这使得返回类型依赖于函数体(不会立即实例化)。不幸的是,这是一个 C++14 特性。

template <typename T>
struct Base
{
decltype(auto) get_value() const { return ((T*)this)->_get_value(); }

protected:
~Base() {}
};
https://godbolt.org/z/r1T56n

这可能由 dcl.spec.auto 涵盖和 temp.inst .

或者,即使在 C++11 中,您也可以通过将函数转换为函数模板来推迟返回类型的确定,必要时依赖于一些虚拟参数:
template <typename T>
struct Base
{
template<typename U=T>
decltype(std::declval<U>()._get_value()) get_value() const {
return ((T*)this)->_get_value();
}

protected:
~Base() {}
};

关于c++ - CRTP派生类方法返回类型的转发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64368517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com