可以为initializer_list字面值重载操作符吗?

Can operators be overloaded for initializer_list literals?

本文关键字:重载 操作符 字面值 list initializer      更新时间:2023-10-16

我正在尝试为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都认为我试图使用他们的非标准块表达式。

GCC:

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

叮当声:

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,

操作符函数要么是非静态成员函数,要么是非成员函数并具有至少有一个类型为的形参:类、类的引用、枚举或对象的引用枚举

这是不可能的。括号初始化列表与std::initializer_list列表不一样,它们是不可互换的。下面的代码应该可以工作:

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

或:

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

Update:澄清一下,重点是语言语法中没有规则允许在op建议的上下文中出现大括号初始化列表。大括号初始化列表只能出现在某些东西即将初始化的上下文中,如果您愿意的话。