【发布时间】:2017-04-15 01:22:54
【问题描述】:
以下代码在 C++11 中编译成功:
#include "json.hpp"
using json = nlohmann::json ;
using namespace std ;
int main(){
json js = "asd" ;
string s1 = js ; // <---- compiles fine
//string s2 = (string)js ; // <---- does not compile
}
它包括JSON for Modern C++。 this wandbox 中有一个工作示例。
JSON 变量 js 被隐式转换为字符串。但是,如果我取消注释最后一行,即显式转换,它将无法编译。编译结果here.
除了这个 json 库的特殊细微差别之外,您如何编写一个类以使隐式转换起作用而显式转换不起作用?
是否有某种构造函数限定符允许这种行为?
【问题讨论】:
-
隐式转换的问题是,程序员通常不知道到底发生了什么,只是转换“有效”。您应该调试有效的代码并单步执行该调用,以查看在
string s1 = js;中发生的实际事件序列,如果它不仅仅是直接调用string构造函数(您正在尝试),我不会感到惊讶与您的评论行有关)。 -
我还没有验证,但它可能使用了模板移动构造函数。
string s2 = move(js);会编译。 -
在任何情况下,你都不应该使用 C 风格的强制转换,并且应该避免不必要的强制转换。
标签: c++ c++11 casting implicit-conversion explicit-conversion