首页 > 解决方案 > C++ 静态成员初始化

问题描述

我正在尝试为 bitset 添加文字。

namespace std {

template <size_t, char...> struct bitset_literal_factory;

template <size_t N, char... cs>
struct bitset_literal_factory<N, '0', cs...> { static bitset<N> value; };

template <size_t N, char... cs>
bitset<N> bitset_literal_factory<N, '0', cs...>::value =
                  bitset_literal_factory<N, cs...>::value;

template <size_t N, char... cs>
struct bitset_literal_factory<N, '1', cs...> { static bitset<N> value; };

template <size_t N, char... cs>
bitset<N> bitset_literal_factory<N, '1', cs...>::value =
                  bitset_literal_factory<N, cs...>::value.set(sizeof...(cs));

template <size_t N>
struct bitset_literal_factory<N, '0'> { static bitset<N> value; };

template <size_t N>
bitset<N> bitset_literal_factory<N, '0'>::value = bitset<N>();

template <size_t N>
struct bitset_literal_factory<N, '1'> { static bitset<N> value; };

template <size_t N>
bitset<N> bitset_literal_factory<N, '1'>::value = bitset<N>().set(0);

namespace bitset_literal {
/* big end */
template <char... cs> bitset<sizeof...(cs)> inline operator""_bs()
{
    return bitset_literal_factory<sizeof...(cs), cs...>::value;
}

}

}

这在使用 gcc 时效果很好,但是当我使用 clang 时,我得到了全零。(例如00111000101_bs

我认为这可能是关于静态成员初始化顺序的问题。然后我按照定义它们的顺序初始化了那个静态成员。所以我尝试另一个例子:

struct bar {
    static int i; 
};

struct foo {
    static int i; 
};

int foo::i = ++bar::i;

int bar::i = 1;   

int main() 
{
    std::cout << foo::i << ' ' << bar::i << std::endl; 
}

这次是 gcc 和 clang print 2 2。那么这是 clang 中的一个错误,还是我的错,因为bitset::set' 的执行顺序未定义?

标签: c++

解决方案


推荐阅读