我在同一个头文件中有两个模板类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
答案 0 :(得分:1)
在定义两个类中的任何一个之前,只需放置前向声明。
#include <iostream>
template<typename> class FirstClass;
template<typename> class SecondClass;
template <typename T>
class FirstClass {
public:
bool convert(const FirstClass<T>& f) { std::cout << "f2f\n"; }
bool convert(const SecondClass<T>& s){ std::cout << "f2s\n"; }
};
template <typename T>
class SecondClass {
public:
bool convert(const FirstClass<T>& f){ std::cout << "s2f\n"; }
bool convert(const SecondClass<T>& s){ std::cout << "s2s\n"; }
};
int main()
{
FirstClass<int> f;
SecondClass<int> s;
f.convert(f);
f.convert(s);
s.convert(f);
s.convert(s);
}
上的输出