1

次のように、同じヘッダー ファイルに 2 つのテンプレート クラス 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 を使用しています

4

1 に答える 1

1

2 つのクラスのいずれかを定義する前に、前方宣言を行うだけです。

#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);        
}

Ideoneでの出力

于 2013-01-18T14:16:01.197 に答える