相关疑难解决方法(0)

初始化程序列表和运算符的RHS

我不明白为什么初始化程序列表不能用于运算符的RHS.考虑:

class foo { };

struct bar
{
    template<typename... T>
    bar(T const&...) { }
};

foo& operator<<(foo& f, bar const&) { return f; }

int main()
{
    foo baz;
    baz << {1, -2, "foo", 4, 5};

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

最新的Clang(gcc也)抱怨:

clang.cc:14:9: error: initializer list cannot be used on the right hand side of operator '<<'
    baz << {1, -2, "foo", 4, 5};
    ^  ~~~~~~~~~~~~~~~~~~~~

    ^  ~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

为什么C++标准会禁止这个?或者换句话说,为什么这会失败而不是

baz << bar{1, -2, "foo", 4, 5};
Run Code Online (Sandbox Code Playgroud)

c++ operators initializer-list c++11

41
推荐指数
1
解决办法
4718
查看次数

为什么我可以在operator + =的右侧使用初始化列表,但不能使用operator +?

这是一个早期问题operator+的后续问题,关于为什么我不能使用大括号括起初始化器作为参数,这是通过查看前面关于该主题的问题来解决的.

考虑以下C++代码,您可以在ideone.com上试用:

#include <iostream>
#include <initializer_list>
using namespace std;

struct AddInitializerList {
    void operator+= (initializer_list<int> values) {
        // Do nothing   
    }

    void operator+ (initializer_list<int> values) {
        // Do nothing
    }
};

int main() {
    AddInitializerList adder;
    adder += {1, 2, 3};  // Totally legit
    adder +  {1, 2, 3};  // Not okay!

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在该生产线main使用operator+了括号内的初始化列表不编译(和,问这个问题前面经过,我现在知道这是为什么).但是,我很困惑为什么使用opeartor+=in 的代码main确实编译得很好.

我很困惑,为什么我可以重载+=并让它工作得很好,而重载+似乎在这里不起作用.标准中是否有特定的规定允许在+= …

c++ operator-overloading initializer-list

22
推荐指数
3
解决办法
2589
查看次数