std::string
在使用与其他基本类型相同的初始化时,我希望以下代码输出“test”而不是“X” 。std::string
现在用 an 调用构造函数,因此调用了forinitializer_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'
}
有没有一种很好的方法可以在不破坏变量初始化的一致外观的情况下做到这一点?