1

std::string在使用与其他基本类型相同的初始化时,我希望以下代码输出“test”而不是“X” 。std::string现在用 an 调用构造函数,因此调用了forinitializer_list的模板特化。getchar

#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'
}

有没有一种很好的方法可以在不破坏变量初始化的一致外观的情况下做到这一点?

4

2 回答 2

4

std::string有一个带initializer_list<char>参数的构造函数;当您将列表初始化与非空花括号初始化列表一起使用时,将始终首先考虑该构造函数,这就是匹配的char特化的原因。get()

如果对所有初始化都使用括号而不是大括号,则initializer_list构造函数将不再是该std::string案例中唯一考虑的构造函数。

auto nbr = int( conf["int"] );
auto dbl = double( conf["dbl"] );
auto str = std::string( conf["str"] );

但是,仅此更改不起作用,因为您有一个可以产生任何类型的隐式用户定义转换模板。在这种情况下,上面的代码std::string会匹配所有std::string可以使用单个参数调用的构造函数。要解决此问题,请使用转换运算符explicit.

struct proxy {
    // use cool parser to actually read values
    template<typename T>
    explicit operator T(){ return get<T>(); }
};

现在,只有显式转换std::string为可行的,并且代码按您希望的方式工作。

现场演示

于 2014-07-29T17:28:58.397 回答
2
auto nbr = (int)conf["int"];
auto dbl = (double)conf["dbl"];
auto str = (string&&)conf["str"];

您已经定义了模板运算符 T(),上面只是调用它。要制作副本,您可以

auto str = string((string&&)conf["str"])

编辑:将 (string) 更改为 (string&&)

EDIT2:以下也有效(全部测试过 - gcc -std=c++11):

auto nbr = (int&&)conf["int"];
auto dbl = (double&&)conf["dbl"];
auto str = (string&&)conf["str"];
于 2014-07-29T17:34:28.113 回答