模板类相互使用会产生歧义错误
Template classes using each other gives ambiguity error
我在同一个头文件中有两个模板类A和B,如下所示:
template <typename T>
class FirstClass {
public:
bool convert(const FirstClass<T>& f){...}
bool convert(const SecondClass<T>& s){...}
};
template <typename T>
class SecondClass {
public:
bool convert(const FirstClass<T>& f){...}
bool convert(const SecondClass<T>& s){...}
};
为了解决任何未知的类错误,我尝试添加一个前向声明:
template <typename T> class SecondClass ; //adding this to the beginning of the file
我得到以下错误:
2 overloads have similar conversions
could be 'bool FirstClass<T>::convert(const FirstClass<T>& )'
or
could be 'bool FirstClass<T>::convert(const SecondClass<T>& )'
while trying to match the argument list '(FirstClass<T>)'
note: qualification adjustment (const/volatile) may be causing the ambiguity
我假设这是因为我正在使用前向声明的类。除了将实现移到Cpp文件(有人告诉我这很麻烦)之外,还有其他有效的解决方案吗?
我在Windows 7上使用VisualStudio 2010
在定义这两个类之前先进行forward声明。
#include <iostream>
template<typename> class FirstClass;
template<typename> class SecondClass;
template <typename T>
class FirstClass {
public:
bool convert(const FirstClass<T>& f) { std::cout << "f2fn"; }
bool convert(const SecondClass<T>& s){ std::cout << "f2sn"; }
};
template <typename T>
class SecondClass {
public:
bool convert(const FirstClass<T>& f){ std::cout << "s2fn"; }
bool convert(const SecondClass<T>& s){ std::cout << "s2sn"; }
};
int main()
{
FirstClass<int> f;
SecondClass<int> s;
f.convert(f);
f.convert(s);
s.convert(f);
s.convert(s);
}
Ideone上的输出
相关文章:
- C++17 中的歧义错误(模板模板参数和默认参数问题)
- 运算符的歧义错误<<自定义 std::ostream 子类中的重载
- 了解函数错误的歧义新声明
- 在C 中,静态成员函数是否继承了?如果是,为什么没有出现歧义错误
- 在 c++ 中使用重载的歧义错误
- 转换 - 错误 E2015,AnsiString(char) 和 AnsiString(short) 之间的歧义
- C++代码中出现歧义错误
- 可变模板和混合的歧义错误
- 错误:"std::copy "之间的重载歧义
- c++操作符string和char*导致歧义错误
- 使用c++ Builder 10 Seattle有很多歧义错误
- c++歧义符号错误
- 函数重载时出现歧义错误
- c++矢量错误,显示变量有歧义-我已经尝试了一切仍然没有希望
- 为什么这两个构造函数一起不会产生歧义错误?
- C2870符号歧义错误
- 由于模板函数声明中存在歧义而导致错误
- 与第三方头文件相关的C++Builder歧义错误
- 模板类相互使用会产生歧义错误
- 错误:对旧声明“double-round(double)”存在歧义