模板上下文中的"不明确的基类"错误
"Ambiguous base class" error in template context
我有这个函数模板:
template <class TemplateArgument, template<class> class TemplateType>
TemplateArgument f(const TemplateType<TemplateArgument>& arg)
{
return TemplateArgument();
}
当这样使用时,它无法编译:
struct A {};
template <typename T> struct S {};
template <typename T> struct B : public S<T> {};
struct C : public B<A> {};
int main()
{
f(C());
return 0;
}
错误消息是:
<source>: In function 'int main()':
<source>:15:10: error: no matching function for call to 'f(C)'
f(C());
^
<source>:2:18: note: candidate: template<class TemplateArgument, template<class> class TemplateType> TemplateArgument f(const TemplateType<TemplateArgument>&)
TemplateArgument f(const TemplateType<TemplateArgument>& arg)
^
<source>:2:18: note: template argument deduction/substitution failed:
<source>:15:10: note: 'const TemplateType<TemplateArgument>' is an ambiguous base class of 'C'
f(C());
^
发生在 GCC(任何版本(和 clang (任何版本(中。MSVC 不会发生。现场演示:https://godbolt.org/g/eWxeHJ
为什么会发生此错误?我没有看到任何歧义,"模棱两可的基类"错误通常发生在多重继承情况下,不是吗? 如何使我的代码编译(正确推断模板参数(?
请注意,我无法编辑A
、B
、C
、S
类及其相互关系,我只能编辑我的函数f()
以正确接受这些类。
编译器不确定是将arg
的类型推断为B<A>
还是S<A>
。我不确定这种特定情况,但众所周知,MSVC 违反了标准,尤其是在模板方面。
至于你的函数,你需要通过显式转换为适当的基础来自己解决这种歧义:
f((const B<A> &)C());
或者通过显式指定模板参数:
f<A, B>(C());
通常,每当语言中存在任何歧义时,编译器永远不会自动解决它,因为它只是对用户意图的猜测,在某些情况下可能是对的,而在另一些情况下则完全错误。
相关文章:
- 当初始值设定项是基类名时'initializer does not name a non-static data member or base class'错误
- 错误:基类在从基类父派生类 Son 时未定义
- 通过基类引用派生类后打印的错误值
- 模板上下文中的"不明确的基类"错误
- 基类未定义.错误 C2504
- 尝试在我的基类中启动线程时,Visual Studio 由于调试错误而中止我的程序
- C 错误:从(基类模板)到子类的无效转换
- 枚举作为基类的模板参数总是会因未解决的错误而失败
- 尝试访问基类的受保护数据成员时出现编译错误
- 尝试从基类访问受保护的构造函数时出现错误 C2248
- 为什么将好奇模板模式的基类直接转换为另一个基类是错误的?
- 尝试通过基类指针访问派生的类成员函数将导致什么样的错误
- 在派生类CTOR中接收基类副本是错误的吗?
- C++头文件错误:基类未定义
- 为什么当我有两个函数时编译器没有显示错误,一个将采用基类,一个将派生类作为参数
- 在基类指针向量中,如何访问派生的类成员返回错误
- 错误:基类'A1'具有私有复制构造函数
- 正在将Visual C++项目迁移到Visual Studio 2013-DirectShow基类错误C2169
- 指向基类错误成员函数的指针
- C++基类错误