gpt4 book ai didi

c++ - 虚拟继承、显式实例化——返回派生类引用/指针(协变类型)

转载 作者:行者123 更新时间:2023-11-28 05:33:11 25 4
gpt4 key购买 nike

.hpp

template <typename T>
struct A { virtual A& modify() = 0; };

template <typename T>
struct B : virtual A<T> {};

template <typename T>
struct C : B<T> { C& modify() final; };

.cpp

template <typename T>
C<T>& C<T>::modify() {
// …
return *this;
}

// explicit instantiation
template struct C<double>;

我需要一些方法来返回引用,以便制作“链”/定义赋值运算符等:

C<double> a, b, c;
// …
a = (b = c).modify();

我还必须处理虚拟继承以避免“菱形问题”(为简单起见此处省略)。

但是,这不起作用:

MSVC:

Error C2908: explicit specialization; 
'A<T> &C<T>::modify(void)' has already been instantiated

显式实例化在没有虚拟继承的情况下工作良好。所以我想知道这里出了什么问题。(如果没有返回对象引用/指针的成员函数,则一切正常。)

最佳答案

显式实例化的正确语法应该是:

template struct C<double>;
^^^^^

此外,您仍然需要为您的 C 模板指定类型参数:

C<double> a, b, c;
^^^^^^

至少 g++ 和 clang 接受这个代码:http://coliru.stacked-crooked.com/a/23ba6a238a7a17da

但 Visual Studio 不...


看起来 VS 不喜欢协变返回类型,以下在 g++/clang 和 VS 下编译但是 - modified() 中没有协变返回:http://coliru.stacked-crooked.com/a/70c8e64f0824129a

关于c++ - 虚拟继承、显式实例化——返回派生类引用/指针(协变类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38935546/

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