模板类相互使用会产生歧义错误

Template classes using each other gives ambiguity error

本文关键字:歧义 错误      更新时间:2023-10-16

我在同一个头文件中有两个模板类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上的输出