模板和隐式构造函数的类定义之外的友元声明

Friend declaration outside the class definition for template and implcit constructor

本文关键字:定义 友元 声明 构造函数      更新时间:2023-10-16

我希望我的重载运算符+适用于混合类型。非模板类没有问题。 为了使它与模板类一起使用,我在类中添加了一个朋友运算符+,它可以工作。

template <typename T> class Wrapper
{
T _val;
public:
Wrapper(T val) :_val(val){}
T getValue() const { return _val; }
friend Wrapper<T> operator+(const Wrapper<T>& val1, const Wrapper<T>& val2)
{
return Wrapper<T>(val1.getValue() + val2.getValue());
}
};
int main()
{
Wrapper<int> v1 = 10; // OK, implicit constructor
Wrapper<int> v2(20);
Wrapper<int> result1 = v1 + v2; // OK, both values are of type Wrapper<int>
Wrapper<int> result2 = v1 + 40; // Ok, casting by implicit constructor works
return 0;
}

现在我想像这样将运算符+实现移到类之外:

#include <iostream>
#include <string>
template <typename T> class Wrapper;
template <typename T> Wrapper<T> operator+(const Wrapper<T>& val1, const Wrapper<T>& val2);
template <typename T> class Wrapper
{
T _val;
public:
Wrapper(T val) :_val(val){}
T getValue() const { return _val; }
friend Wrapper<T> operator+ <>(const Wrapper<T>& val1, const Wrapper<T>& val2);
};
// template<class T> Wrapper<T> operator+(const Wrapper<T>&, const Wrapper<T>&)
// template argument deduction/substitution failed
template <typename T> Wrapper<T> operator+(const Wrapper<T>& val1, const Wrapper<T>& val2)
{
return Wrapper<T>(val1.getValue() + val2.getValue());
}
int main()
{
Wrapper<int> v1 = 10; // OK, implicit constructor
Wrapper<int> v2(20);
Wrapper<int> result1 = v1 + v2; // OK, both values are of type Wrapper<int>
// note: mismatched types 'const Wrapper<T>' and 'int'
Wrapper<int> result2 = v1 + 40; // Error
return 0;
}

但它给了我编译错误(将它们粘贴到上面的代码中(。 可以修复它吗?

http://cpp.sh/5j5zg(工作( http://cpp.sh/9saow(不工作(

制作这种不是模板函数的友元函数有点奇怪。但是,您可以通过将friend operator+设置为模板函数来对其进行一些更改以使其工作:

template <typename T>
class Wrapper
{
T _val;
public:
Wrapper(T val) :_val(val){}
T getValue() const { return _val; }
template <typename U>
friend Wrapper<U> operator+(const Wrapper<U>& val1, const Wrapper<U>& val2);
};
template <typename T>
Wrapper<T> operator+(const Wrapper<T>& val1, const Wrapper<T>& val2)
{
return Wrapper<T>(val1.getValue() + val2.getValue());
}

这几乎可以按您的预期工作,但由于这是一个模板函数,因此隐式转换被禁用。不过,将它们重新添加起来很容易:

template <typename T>
Wrapper<T> operator+(const Wrapper<T>& val1, const T& val2)
{
return Wrapper<T>{ val1.getValue() + val2 };
}
template <typename T>
Wrapper<T> operator+(const T& val1, const Wrapper<T>& val2)
{
return Wrapper<T>{ val1 + val2.getValue() };
}

住在科里鲁