Rob*_*ahl 11 c++ rvalue c++11 visual-studio-2012
我正在尝试更新使用visual studio 2005构建的旧项目以使用visual studio 2012,我收到的错误是我无法解决的.
在VS2005下运行良好的代码:
#include <iostream>
#include <string>
#include <sstream>
using std::cout;
using std::wcout;
using std::endl;
using std::wstring;
using std::string;
class Value
{
public:
Value(const wstring& value)
{
v = value;
}
Value(Value& other)
{
this->v = other.v;
}
template<typename T>
operator T() const
{
T reply;
std::wistringstream is;
is.str(v);
is >> reply;
return reply;
}
operator wstring() const
{
return v;
}
private:
wstring v;
};
int main()
{
Value v(L"Hello World");
wstring str = v;
wcout << str << endl;
Value int_val(L"1");
int i = int_val;
cout << i + 1 << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我在VS2012下编译时,我在"wstring str = v;"行上出现错误,错误是:
error C2440: 'initializing' : cannot convert from 'Value' to 'std::basic_string<_Elem,_Traits,_Alloc>'
1> with
1> [
1> _Elem=wchar_t,
1> _Traits=std::char_traits<wchar_t>,
1> _Alloc=std::allocator<wchar_t>
1> ]
1> No constructor could take the source type, or constructor overload resolution was ambiguous
Run Code Online (Sandbox Code Playgroud)
我可以通过将运算符签名从'operator wstring()const'更改为'operator const wstring&()const'来修复它.但是为什么原始代码不起作用,即使它在VS2005中有效.
我没有在"int i = int_val;"行上收到错误.
这也可以在cygwin(版本4.5.3)中使用GCC(g ++)进行编译和运行.
更新 为了真正模拟我的真实问题,上面的示例代码中遗漏了一些信息.在Value类和用法之间是一些其他类.一个看起来像这样:
class Config
{
public:
virtual Value getValue(const string& key) const = 0;
Value operator()(const string& key)
{
return getValue(key);
}
};
Run Code Online (Sandbox Code Playgroud)
用法const wstring value2 = config("key");
这将在编译时给出上述错误,但IntelliSense将提供有关错误的其他提示,它说:"从"值"到"const std :: wstring"的多个用户定义转换适用:"并且它指向两者常规构造函数和basic_string的移动构造函数.因此它似乎与rvalues有关,我一直在阅读,并了解基础知识.但是我可能会失踪很多.
我发现我可以通过将用法更改为:const wstring && value = config("key")来解决此问题;
然后看起来VS2012编译器理解它应该使用哪个构造函数.
问题:*在这个例子中有没有办法不使用&&?*这里到底发生了什么?
我在GitHub上提供了示例代码:https: //github.com/Discordia/ImplicitTypeConversion
| 归档时间: |
|
| 查看次数: |
1324 次 |
| 最近记录: |