VS2013中的转换运算符错误C2678,在VS2008中工作 [英] Conversion operator error C2678 in VS2013, works in VS2008
问题描述
我有一段代码在VS2008中成功编译,无法在VS2013中编译。
有一个类 Data :: CData
,这是一个变体类型实现。它有一个转换运算符重载:
模板< class T&夯; GetValue();
template< class T> const T& GetValue()const;
template< class T>运算符T&(){return GetValue< T>(); }
template< class T>运算符const T&()const {return GetValue< T>(); }
产生错误的代码是
Data:CData Val;
Data :: PParams Prm =(const Data :: PParams&)Val;
错误是:error C2678:binary'=':无操作符,
这两个编译器都成功编译了这个代码:
Data :: CData Val;
Data :: PParams Prm = Val.operator const Data :: PParams&();
我怎么了?
重现问题的示例: https://www.dropbox.com/s /zjohnu5v87tyr2c/ConstOverload.zip?dl=0
我终于有了解决方案!
而不是两个操作符重载我用来
模板< class T&运算符T&(){return GetValue< T>(); }
template< class T>运算符const T&()const {return GetValue< T>(); }
应该有三个
模板< class T>运算符T&(){return GetValue< T>(); }
template< class T>运算符const T&(){return GetValue< T>(); }
template< class T>运算符const T&()const {return GetValue< T>(); }因此,在VS2013中,我们还需要一个专用的操作符来从非const对象中获取const引用。如果有人找到它的定义的官方文件,请张贴在这里链接。希望这个答案将帮助别人。
I have a piece of code that is succesfully compiled in VS2008 and fails to compile in VS2013.
There is a class Data::CData
which is a variant type implementation. It has a conversion operator overloading:
template<class T> T& GetValue();
template<class T> const T& GetValue() const;
template<class T> operator T&() { return GetValue<T>(); }
template<class T> operator const T&() const { return GetValue<T>(); }
The code that produces an error is
Data::CData Val;
Data::PParams Prm = (const Data::PParams&)Val;
The error is: error C2678: binary '=' : no operator found which takes a left-hand operand of type 'const Data::PParams' (or there is no acceptable conversion).
And this code is successfully compiled by both compilers:
Data::CData Val;
Data::PParams Prm = Val.operator const Data::PParams&();
What do I do wrong?
Example that reproduces a problem: https://www.dropbox.com/s/zjohnu5v87tyr2c/ConstOverload.zip?dl=0
解决方案 I finally got a solution!
Instead of two operator overloads I used to
template<class T> operator T&() { return GetValue<T>(); }
template<class T> operator const T&() const { return GetValue<T>(); }
there should be three
template<class T> operator T&() { return GetValue<T>(); }
template<class T> operator const T&() { return GetValue<T>(); }
template<class T> operator const T&() const { return GetValue<T>(); }
So, in VS2013 we also need a dedicated operator to get const reference from non-const object. If someone find an official document where it is defined, post link here please. Hope this answer will help others.
这篇关于VS2013中的转换运算符错误C2678,在VS2008中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!