我正在尝试使用 auto
进行重载返回类型 (C++11)
我已经阅读了 C++ template operator overloading with different types ,但这并不是我想要做的。
我有这样一个类:
template<typename T>
class Attr
{
public:
Attr(const T& v) : value(v) {};
typedef T type;
T value;
}
现在我尝试添加一些运算符(=
,+
,-
,*
,/
,%
)和auto
返回类型,所以我在里面添加 Attr
这段代码:
template<typename U> T& operator=(const U& v){value=v;return value;}; //work
template<typename U>
auto operator+(const U& v) -> std::decltype(Attr<T>::type+v) const //line 29
{
return value+v;
}; //fail
我尝试替换 std::decltype(Attr<T>::type+v)
与:
-
std::decltype(value+v)
-
std::decltype(Attr<T>::value+v)
-
std::decltype(T()+v)
我也尝试删除 const
,但没有变化,我总是有这些错误:
ORM/Attr.hpp:29:47: erreur: expected type-specifier
ORM/Attr.hpp:29:47: erreur: expected initializer
编辑:
一、decltype
不是 std
的成员.
应该是:
template<typename U> auto operator+(const U& v)const -> decltype(value+v) {return value-v;};
最终代码:
template<typename T>
class Attr
{
public:
Attr(const T& v) : value(v) {};
typedef T type;
T value;
template<typename U> auto operator+(const U& v)const -> decltype(value+v) {return value-v;};
}
最佳答案
第一个问题
没有std::decltype
这样的东西. decltype
是关键字。其次,在decltype
里面您正在尝试添加对象和类型的表达式。虽然我明白你的意思,但对于编译器来说,这是无意义的。
你可以使用 std::declval<>
为此目的:
template<typename U>
auto operator+(const U& v) ->
decltype(std::declval<T>()+v) const //line 29
{
return value+v;
};
或者,如果您已经声明了您的 value
数据成员 before 在成员函数主体之外引用它的点之前,您可以:
template<typename U>
auto operator+(const U& v) ->
decltype(value + v) const
// ^^^^^
// Valid only if the "value" data member has been declared before
{
return value+v;
};
第二个问题
通常,operator +
被定义为(可能是 friend )自由函数,而不是成员函数,因此即使您的类型的对象未作为第一个操作数传递,您也可以实际使其工作。
关于C++ 模板运算符重载不同类型,自动返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16736607/