繁体   English   中英

std :: pair数组的聚合初始化

[英]Aggregate initialization for array of std::pair

怀疑,使用花括号初始化std::pair不起作用,因为std::pair不是聚合。

std::pair <int, int> p = {1,2}; // Doesn't work

但是,初始化std::pair数组效果很好(在gcc 4.9有警告)

std::pair <int, int> a_p[] = {
    {1,2},
    {3,4},
    {5,6}
}; // Works fine

为什么会这样?

编辑:此问题已被标记为具有非静态成员初始化程序的类C ++ 11聚合初始化的可能重复但是,这个问题没有谈论非静态成员初始化程序,AFAIK, std::pair有一个用户定义的构造函数。 引自http://en.cppreference.com/w/cpp/header/utility

template <class T1, class T2>
struct pair {
    typedef T1 first_type;
    typedef T2 second_type;

    T1 first;
    T2 second;
    pair(const pair&) = default;
    pair(pair&&) = default;

    constexpr pair();
    pair(const T1& x, const T2& y);
    template<class U, class V> pair(U&& x, V&& y);
    template<class U, class V> pair(const pair<U, V>& p);
    template<class U, class V> pair(pair<U, V>&& p);
    template <class... Args1, class... Args2>
        pair(piecewise_construct_t,
             tuple<Args1...> first_args, tuple<Args2...> second_args);

    pair& operator=(const pair& p);
    template<class U, class V> pair& operator=(const pair<U, V>& p);
    pair& operator=(pair&& p) noexcept(see below);
    template<class U, class V> pair& operator=(pair<U, V>&& p);

    void swap(pair& p) noexcept( noexcept(swap(first, p.first)) &&
                                 noexcept(swap(second, p.second)) );
};

自C ++ 11发布以来,类类型的聚合式初始化(​​“统一初始化”)在过去的5年中是合法的。

较旧版本的gcc默认使用古老的C ++ 03标准(或者更老的C ++ 98),但是它们知道C ++ 11,因此在某些情况下会应用C ++ 11规则,这是相对明确的。 这是警告的含义:

warning: extended initializer lists only available with -std=c++11 or -std=gnu++11

一些甚至更旧版本的gcc可能正在应用他们自己的(pre-C ++ 11)扩展,因此给出不同的警告。

您应该在C ++ 11模式下编译(至少),或者使用默认为C ++ 11或C ++ 14的现代编译器,例如gcc 6.1。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM