c++ - 可以为 initializer_list 文字重载运算符吗?

标签 c++ operator-overloading initializer-list

<分区>

我正在尝试为 std::initializer_list 重载运算符,但以下代码既不在 GCC 4.7.2 也不在 Clang 3.2 中编译:

#include <initializer_list>

void operator+(const std::initializer_list<int>&, const std::initializer_list<int>&);

int main() {
   {1, 2} + {3, 4};
}

13.5/6 规定运算符函数应至少有一个参数,其类型为类、枚举或对其中之一的引用,标准将 initializer_list 指定为模板类,所以对我来说它似乎应该是一致的。但是,显然 Clang 和 GCC 都认为我在尝试使用他们的非标准 block 表达式。

海湾合作委员会:

Compilation finished with errors:
source.cpp: In function 'int main()':
source.cpp:7:8: warning: left operand of comma operator has no effect [-Wunused-value]
source.cpp:7:9: error: expected ';' before '}' token
source.cpp:7:9: warning: right operand of comma operator has no effect [-Wunused-value]
source.cpp:7:13: error: expected primary-expression before '{' token
source.cpp:7:13: error: expected ';' before '{' token

clang :

Compilation finished with errors:
source.cpp:7:5: warning: expression result unused [-Wunused-value]
   {1, 2} + {3, 4};
    ^
source.cpp:7:9: error: expected ';' after expression
   {1, 2} + {3, 4};
        ^
        ;
source.cpp:7:8: warning: expression result unused [-Wunused-value]
   {1, 2} + {3, 4};
       ^
source.cpp:7:13: error: expected expression
   {1, 2} + {3, 4};
            ^
2 warnings and 2 errors generated.

这应该编译吗?如果不是,为什么不呢?

编辑:

毫不奇怪,VS 2012 的 11 月 CTP 也失败了:

error C2143: syntax error : missing ';' before '}'
error C2059: syntax error : '{'
error C2143: syntax error : missing ';' before '{'

最佳答案

据我了解13.5/6,

An operator function shall either be a non-static member function or be a non-member function and have at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration

这应该是不可能的。 Braced-init-lists 与 std::initializer_list 不同,它们不可互换。不过,以下应该有效:

std::initializer_list<int>({1,2}) + std::initializer_list<int>({2,1})

或者这个:

operator+({1,2}, {2,1})

更新:澄清一下,关键是语言语法中没有规则允许括号初始化列表出现在 OP 建议的上下文中。如果您愿意,Braced-init-lists 只能出现在即将初始化某些内容的上下文中。

关于c++ - 可以为 initializer_list 文字重载运算符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14370043/

相关文章:

c++ - 内核模块或用户空间应用程序

c++ - 为什么带有initializer_list参数的模板对字符串的行为不正确?

c++ - strcpy 可以在 Arduino 上编辑内存地址吗?

c++ - 如何重载 operator= 以返回指向成员的指针?

C++ 运算符重载错误

c++ - 使用模板重载运算符,但防止重新定义

c++ - 初始化结构成员时可能出现 MSVC 2013 错误

c++ - 使用 reference_wrappers 初始化 vector

c++ - 显示 vector C++ 的最小值和最大值

c++ - 从文件中提取数据并将其存储在 C++ 中的字符串中