【发布时间】:2014-09-21 04:17:18
【问题描述】:
当使用std::string 使用与其他基本类型相同的初始化时,我希望以下代码输出“test”而不是“X”。 std::string 现在使用initializer_list 调用构造函数,因此调用get 的模板特化char。
#include <sstream>
#include <string>
#include <iostream>
// Imagine this part as some kind of cool parser.
// I've thrown out everything for a simpler demonstration.
template<typename T> T get() {}
template<> int get(){ return 5; }
template<> double get(){ return .5; }
template<> char get(){ return 'X'; }
template<> std::string get(){ return "test"; }
struct Config {
struct proxy {
// use cool parser to actually read values
template<typename T> operator T(){ return get<T>(); }
};
proxy operator[](const std::string &what){ return proxy{}; }
};
int main()
{
auto conf = Config{};
auto nbr = int{ conf["int"] };
auto dbl = double{ conf["dbl"] };
auto str = std::string{ conf["str"] };
std::cout << nbr << std::endl; // 5
std::cout << dbl << std::endl; // 0.5
std::cout << str << std::endl; // 'X'
}
有没有一种很好的方法可以在不破坏变量初始化的一致外观的情况下做到这一点?
【问题讨论】:
-
@Praetorian 你为什么删除你的答案?
-
我的示例在 VS2013 上运行,但 clang 和 gcc 都拒绝它作为对
std::string构造函数的模棱两可的调用,我相信它们是正确的。 -
使用
{}从元素列表(包括一或零)构造一个元素,在所有其他情况下使用()。这个问题就是为什么。 -
嘎啊啊。为什么
std::string甚至有一个初始化列表构造函数?谁来写std::string mystr{'h','e','l','l','o',' ','w','o','r','l','d'}?我想您可能正在编写二进制字符或其他东西的初始化列表,但即使那样我也不确定初始化列表是否会更容易。
标签: c++ c++11 initializer-list list-initialization