这是我的代码:
#include <vector>
struct A
{
typedef std::vector<int> vec; //(1) template type
virtual A& test(vec) = 0;
};
struct B : public virtual A //(2) virtual inheritance
{
virtual B& test(vec) override //(3) covariant return type
{
return *this;
}
};
//std::vector<int> vv, cc(vv); //(4) explicit instantiate copy-ctor
int main()
{
B b;
b.test({});
}
Visual C++ 2013 给我一个链接错误。
error LNK2001: unresolved external symbol "public: __thiscall
std::vector<int,class std::allocator<int> >::vector<int,class
std::allocator<int> >(class std::vector<int,class
std::allocator<int> > const &)"
(??0?$vector@HV?$allocator@H@std@@@std@@QAE@ABV01@@Z)
我试过 gcc,它可以编译。
如果我做了以下任何一件事情,VC 就会编译:
- 将第(1)行改为非模板类型
- 去掉第(2)行中的“virtual”
- 将第(3)行的返回类型改为A&
- 取消第(4)行的注释
为什么?
最佳答案
这确实可能是一个 VC 错误; Clang 和 G++ 都接受此代码。有趣的是,将代码更改为在调用 B.test()
时不使用初始化列表,如下所示也消除了错误,这让我相信导致此问题的原因是 VC++ 的初始化列表支持问题。
#include <vector>
struct A
{
typedef std::vector<int> vec; //(1) template type
virtual A& test(vec) = 0;
};
struct B : public virtual A //(2) virtual inheritance
{
virtual B& test(vec) override //(3) covariant return type
{
return *this;
}
};
//std::vector<int> vv, cc(vv); //(4) explicit instantiate copy-ctor
int main()
{
A::vec v;
B b;
//b.test({});
b.test(v);
}
关于c++ - 具有协变返回类型和模板类参数的虚拟继承,vs2013 中的 LINK 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26042254/