【发布时间】:2014-04-17 17:35:16
【问题描述】:
是否可以重载在初始化列表中使用时只接受空白字符串的构造函数?
struct null_ptr_type;
struct str
{
str(null_ptr_type*) {}
str(const char(&)[1]) {}
};
struct config
{
str s;
};
int main()
{
config c1 = {0}; // Works, implicit conversion to a null pointer
config c2 = {str("")}; // Works
config cx = {str("abc")}; // Fails (as desired)
config c3 = {""}; // Fails with no conversion possible
}
有没有办法让c3 的语法在不接受非空字符串的情况下工作?鉴于c1 有效,我不明白为什么它不这样做。是否有一些我在这里遗漏的规则禁止这样做?
【问题讨论】:
-
FWIW, VS 2013 如您所料调用隐式转换。不是我所知道的最好的参考,但它是一些东西。
-
谢谢,也许我应该指定:
g++ (Ubuntu/Linaro 4.7.3-2ubuntu1~12.04) 4.7.3,但很高兴听到它在某处工作。 :) -
clang++3.5 也接受这种转换。
-
你不能给它一个默认值,所以你会做 config(string fred = ""); ?
-
你为什么要这个?我想不出任何理由。
标签: c++