2013-08-01 164 views
1

爲什麼我在下面得到鏈接器錯誤?模板好友功能實例化

template<typename T, typename U> 
class A { 
public: 
    class B; 
}; 

template<typename T, typename U> 
class A<T, U>::B { 
    friend bool operator==(const B& b1, const B& b2); 
}; 

template<typename T, typename U> 
bool operator==(const typename A<T, U>::B& b1, const typename A<T, U>::B& b2) { 
    return true; 
} 

int main() { 
    A<char, int>::B b1; 
    A<char, int>::B b2; 

    if (b1 == b2) { 
     return 0; 
    } else { 
     return 1; 
    } 
} 

我得到的錯誤是:

Undefined symbols for architecture x86_64: 
    "operator==(A<char, int>::B const&, A<char, int>::B const&)", referenced from: 
     _main in test-qSCyyF.o 

回答

2

因爲你調用它,它沒有定義!

template<typename T, typename U> 
class A<T, U>::B { 
    friend bool operator==(const B& b1, const B& b2); 
}; 

A<T,U>::B類的非模板友元函數的聲明。

它與呼叫(b1 == b2)的匹配程度與您在下面定義的模板運算符相同,但它是首選的,因爲它是非模板。

GCC甚至給出了-Wnon-template-friend

警告的警告:朋友宣言 '布爾運算符==(const的一個:: B &,常量一個:: B &)' 聲明一個非模板函數[ - Wnon模板,朋友]
注:(後這裏的函數名,如果這不是您的本意,請確保該函數模板已經聲明,並添加<>)

要解決,它提供定義

template<typename T, typename U> 
class A<T, U>::B { 
    friend bool operator==(const B& b1, const B& b2) { 
     return true; 
    } 
}; 

並擺脫模板操作符或只保留一個模板。

+0

那麼...我該如何解決它。 = P – fumoboy007

+0

我認爲這將是obvius :)我會更新。 – jrok

+0

所以我不能有一個模板化的朋友函數,它是在類之外定義的? – fumoboy007