C ++静态成员初始化

时间:2018-05-25 03:41:57

标签: 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打印2 2。这是clang中的一个错误,还是我的错,因为bitset::set执行的顺序是未定义的?

0 个答案:

没有答案