Conversion operator error C2678 in VS2013, works in VS2008

跟風遠走 提交于 2019-12-11 08:15:50

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/25818818/conversion-operator-error-c2678-in-vs2013-works-in-vs2008

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!