C++左手赋值运算符
c++ left hand assignment operator
我有一个 class(应该包含任何值),如下所示:
class Value
{
public:
Value();
Value(const Value& value);
virtual ~Value();
void operator= (const Value& value);
template<class T>
void operator= (T value);
...
}
现在我的问题是:
为什么我不能为此 class 实现赋值运算符,如下所示:
template<class T>
void operator=(T& value, const Value& v)
{...}
我想设计一个 class 其工作原理如下:
Value v;
v = 'c';
v = 13;
v = 5.6;
int i = 5;
v = &i;
int y = v;
char b = v;
我想将任何数据类型放入其中或从中取出。
目前这适用于:
v = 'c';
v = 13;
v = 5.6;
但不适用于:
int y = v;
有效的是:
int y = v.get<int>();
但这不如
int y = v;
会是
因为标准规定赋值运算符必须是只有一个参数的成员函数
13.5.3$1 作业 [over.ass]:
An assignment operator shall be implemented by a non-static member function with exactly one parameter.
您可以像这样实现类型转换运算符
operator int()
{
if(current_value_is_not_int)
throw MyException("Current value is not int");
//return int value
}
您可以通过向 class 添加模板类型转换来轻松修复编译错误,如下所示:
class Value
{
...
template <class T> operator T();
};
Value va;
int i = va;
我仍然相信您会发现自己实施 'boost::any' 的任务非常具有挑战性,但为什么不呢? :)
我有一个 class(应该包含任何值),如下所示:
class Value
{
public:
Value();
Value(const Value& value);
virtual ~Value();
void operator= (const Value& value);
template<class T>
void operator= (T value);
...
}
现在我的问题是:
为什么我不能为此 class 实现赋值运算符,如下所示:
template<class T>
void operator=(T& value, const Value& v)
{...}
我想设计一个 class 其工作原理如下:
Value v;
v = 'c';
v = 13;
v = 5.6;
int i = 5;
v = &i;
int y = v;
char b = v;
我想将任何数据类型放入其中或从中取出。 目前这适用于:
v = 'c';
v = 13;
v = 5.6;
但不适用于:
int y = v;
有效的是:
int y = v.get<int>();
但这不如
int y = v;
会是
因为标准规定赋值运算符必须是只有一个参数的成员函数
13.5.3$1 作业 [over.ass]:
An assignment operator shall be implemented by a non-static member function with exactly one parameter.
您可以像这样实现类型转换运算符
operator int()
{
if(current_value_is_not_int)
throw MyException("Current value is not int");
//return int value
}
您可以通过向 class 添加模板类型转换来轻松修复编译错误,如下所示:
class Value
{
...
template <class T> operator T();
};
Value va;
int i = va;
我仍然相信您会发现自己实施 'boost::any' 的任务非常具有挑战性,但为什么不呢? :)