【问题标题】:How to prevent std::string from using the initializer_list constructor?如何防止 std::string 使用 initializer_list 构造函数?
【发布时间】: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


【解决方案1】:

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

如果对所有初始化都使用括号而不是大括号,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 是可行的,并且代码可以按照您希望的方式运行。

Live demo

【讨论】:

    【解决方案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"];
    

    【讨论】:

    • (string)conf["str"] 或 string(conf["str"]) 在 gcc 上编译失败
    • 你说得对,我们需要 (string&&)conf["str"] 来匹配 get()
    • (string&amp;&amp;)conf["str"] 破坏了一致性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多