2013-02-28 4 views
5

나는 친구 템플릿 함수로 템플릿 클래스를 가지고있다. 저는 현재 다음과 같은 코드를 가지고 있고 그것은 노력 : 나는 보안 혜택이 제공 일대일 대응을 할 수 있도록 내 솔루션은 친구 기능의 앞으로 선언을하는앞으로 템플릿 선언 함수

template<class T> 
class Vector 
{ 
    public: 
    template<class U, class W> 
    friend Vector<U> operator*(const W lhs, const Vector<U>& rhs); 
} 

template<class U, class W> 
Vector<U> operator*(const W lhs, const Vector<U>& rhs) 
{ 
    // Multiplication 
} 

내가 선호 내 현재 방법에 비해. 다음과 같은 시도했지만 오류가 계속 실행.

template<class T> 
class Vector; 

template<class T, class W> 
Vector<T> operator*(const W lhs, const Vector<T>& rhs); 

template<class T> 
class Vector 
{ 
    public: 
    friend Vector<T> (::operator*<>)(const W lhs, const Vector<T>& rhs); 
} 

template<class T, class W> 
Vector<T> operator*(const W lhs, const Vector<T>& rhs) 
{ 
    // Multiplication 
} 
+1

원래 'friend' 선언을 사용하지 마십시오. –

+0

원래 버전에서는 Vector의 모든 템플릿 인스턴스화가 연산자 *의 모든 템플릿 인스턴스화를 사용하는 친구입니다. 나는 벡터가 모든 다른 템플릿 인스턴스화가 친구가되도록 허용하지 않는 두 번째 솔루션을 선호합니다. – noddy

답변

3

나는 거의 그렇게 생각합니다. 함수를 친구가되면 단일 매개 변수 템플릿으로 만들면됩니다. 다음은 g ++ 4.5에서 컴파일되지만 테스트 케이스로 인스턴스화를 테스트 할 수 없기 때문에 실제 문제를 100 % 확신 할 수는 없습니다.

template<class T> 
class Vector; 

template<class T, class W> 
Vector<T> operator*(const W lhs, const Vector<T>& rhs); 

template<class T> 
class Vector 
{ 
    public: 
    template<class W> 
    friend Vector<T> operator*(const W lhs, const Vector<T>& rhs); 
}; 

template<class T, class W> 
Vector<T> operator*(const W lhs, const Vector<T>& rhs) 
{ 
    // Multiplication 
} 
+0

코드가 컴파일되지만 [링크를 얻습니다] (http://ideone.com/KIT4lV). friend 함수와 free 함수 템플릿은 다른 공제입니다. – WhozCraig

+0

GNU 컴파일러를 사용하여 WhozCraig와 동일한 오류가 발생합니다. 그러나 Visual Studio C++에서 작동합니다. – noddy