2016-07-05 52 views
2

我想超载'+'运营商类模板,但得到解析外部符号错误使用中缀符号调用它:解析的外部符号错误重载运算符+模板

// In main.cpp 

template<class T> 
struct B 
{ 
    B(T t) : t_(t) {} 
    friend B operator+(B const &lhs, B const &rhs); 
    T t_; 
}; 

template<class T> 
B<T> operator+(B<T> const &lhs, B<T> const &rhs) 
{ 
    return B<T>(lhs.t_ + rhs.t_); 
} 

int main() 
{ 
    B<int> b = 1; 
    b = operator+<int>(b, 2); // works but clunky syntax 
    // b = b + 2; // LNK2019: unresolved external symbol 
} 

它工作正常,定期的非模板如此想知道是否有可能在这里实现同样的事情。

我使用Visual C++ 2015年

+1

'地图B运营商+(B常量和LHS,B常量'是不是一个模板声明,但是你定义一个 – LogicStuff

+0

还HTTP看到: //stackoverflow.com/questions/11864102/why-is-friend-member-function-not-recognized-as-function-template-automatically –

+0

顺便说一句,目前所有的成员都是“公共”,所以不需要“朋友”; - ) – Jarod42

回答

3
friend B operator+(B const &lhs, B const &rhs); 

是一个非模板函数。

更简单的将其定义inline

template<class T> 
struct B 
{ 
    B(T t) : t_(t) {} 
    friend B operator+(B const &lhs, B const &rhs) 
    { 
     return B(lhs.t_ + rhs.t_); 
    } 
    T t_; 
}; 

Demo

否则,您必须声明的所有模板的朋友

template <typename T> struct B; 

template <typename T> B<T> operator+(B<T> const &lhs, B<T> const &rhs); 

template<class T> 
struct B 
{ 
    B(T t) : t_(t) {} 

    template <typename U> 
    friend B<U> operator+(B<U> const &lhs, B<U> const &rhs); 
    T t_; 
}; 

Demo

或只是特定的一个

template <typename T> struct B; 

template <typename T> B<T> operator+(B<T> const &lhs, B<T> const &rhs); 

template<class T> 
struct B 
{ 
    B(T t) : t_(t) {} 
    friend B operator+<>(B const &lhs, B const &rhs); 
    // Note the <> 

    T t_; 
}; 

template<class T> 
B<T> operator+(B<T> const &lhs, B<T> const &rhs) 
{ 
    return B<T>(lhs.t_ + rhs.t_); 
} 

Demo

+0

定义它的内联工作,但我想避免这种情况,因为我的真实课堂上有更多的内容。我发现我没有定义模板函数,但是我尝试了你的解决方案,并且在两种情况下都得到'C2678:binary'+':找不到操作符,它需要一个类型为'B '的左手操作数(或者没有可接受的转换)'。 –

+0

@GeorgeSkelton:我添加了链接。 – Jarod42

+0

好的,我明白你的意思了。但它仍然不会编译'b + 1',因为它不能从'int'推导出'B '。但是一个成员函数可以做出这样的推论。这只是朋友功能的内在限制吗? –

0

你还没有把它定义为类中的模板。 最简单的办法是定义在类中的功能(内置):

template<class T> 
struct B 
{ 
    B (T t) : t_ (t) {} 
    friend B operator+ (const B &lhs, const B &rhs) 
    { 
     return B (lhs.t_ + rhs.t_); 
    } 
    T t_; 
};