gpt4 book ai didi

c++ - 重载 C++ 模板类虚函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:19:06 24 4
gpt4 key购买 nike

下面是重现我遇到的问题的代码。 Base class 是一个带有虚函数的模板类 foo . foo具有添加传入参数的默认实现。

SimpleDerived源自 Base , 用 std::string 专门化它. SimpleDerived重载虚拟 Base<T>::foo()功能。此类编译良好及其 foomain 中调用时按预期输出.

#include <iostream>

template<class T>
struct Base
{
virtual void foo(T val)
{
T local = val + val; // THE OFFENDING LINE OF CODE
std::cout << "Base" << std::endl;
}
};

struct SimpleDerived : public Base<std::string>
{
virtual void foo(std::string val)
{
std::cout << "SimpleDerived" << std::endl;
}
};

struct SimpleObject
{
int value;
};

struct ComplexDerived : public Base<SimpleObject>
{
virtual void foo(SimpleObject val)
{
std::cout << "ComplexDerived" << std::endl;
}
};

int main(void)
{
Base<int> base;
base.foo(2);

SimpleDerived simpleDerived;
simpleDerived.foo("hello world");

SimpleObject object;
ComplexDerived complexDerived;
complexDerived.foo(object);

return 0;
}

ComplexDerived源自 Base , 用自定义结构专门化它 SimpleObject . ComplexDerived重载 foo以及。然而,这就是问题的根源。如果我尝试编译它,我会得到:

quicktest.cpp: In member function ‘void Base<T>::foo(T) [with T = SimpleObject]’:
quicktest.cpp:47:1: instantiated from here
quicktest.cpp:8:19: error: no match for ‘operator+’ in ‘val + val’

显然,SimpleObject 没有运算符“+” .但这是我的困惑..要求编译器实现 Base<SimpleObject>::foo因为这就是ComplexDerived继承自。但是,我从不使用或调用 Base<SimpleObject>::foo .那么编译器应该尝试生成这个基类函数吗?

最佳答案

C++11 标准第 14.7.1/10 段规定:

An implementation shall not implicitly instantiate a function template, a member template, a non-virtual member function, a member class, or a static data member of a class template that does not require instantiation. 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. [...]

换句话说,这种情况下的行为是特定于实现的。

虽然理论上编译器可以发现对基类的 foo() 实现的调用永远不会被调用(因为函数调用不会通过引用或指针发生)并避免实例化它,此行为不是标准强制要求的。

关于c++ - 重载 C++ 模板类虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17118294/

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