gpt4 book ai didi

c++ - 可能模板失败的继承

转载 作者:行者123 更新时间:2023-11-30 03:58:57 26 4
gpt4 key购买 nike

依赖于模板扩展的方法中的错误只会在显式调用该方法时给出编译器错误。尽管当该方法被标记为虚拟时,无论是否实际调用它都会产生编译器错误。 C++ 标准中是否有任何内容可以解释为什么将这些方法标记为虚拟会导致编译器错误?

#include <memory>
#include <iostream>

template <class T_>
class Foo
{
protected:
T_ data;
public:
Foo(const T_& x) : data(x) { }

Foo(T_&& x) : data(std::move(x)) { }

// comment these two lines out and it works fine.
virtual void test(T_& x) = 0;
virtual void test(T_&& x) = 0;
};

template <class T_>
class Bar : public Foo<T_>
{
public:
using Foo<T_>::Foo;

void test(T_& x)
{
std::cout << "test(&)" << std::endl;
x = this->data;
}

void test(T_&& x)
{
std::cout << "test(&&)" << std::endl;
x = std::move(this->data);
}
};

int main()
{
Bar<std::unique_ptr<int>> x(std::unique_ptr<int>(new int(42)));
}

最佳答案

virtual 的覆盖程序函数总是 odr-used - 也就是说,它们的定义必须存在,无论它们是否在翻译单元中明确使用。
virtual 的覆盖功能本身就是virtual ([class.virtual]/2) 和所有 virtual必须定义函数([basic.def.odr]/3 和 4)。

现在的问题是 test派生类中的重载实际上是实例化的。对于模板,标准要求

Unless a member of a class template […] has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist;

对于虚函数,有人可能会争辩说它们的存在足以要求定义。然而,该标准并没有束缚自己,而是将决定留给了实现,[temp.inst]/11:

It is unspecified whether or not an implementation implicitly instantiates a virtual member function of a class template if the virtual member function would not otherwise be instantiated.

关于c++ - 可能模板失败的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27158330/

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