c++ - 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
' 的执行顺序未定义?
解决方案
推荐阅读
- android - 如何在android中实现带有领域的分页库?
- php - 与 Mersenne Twister 的疯狂巧合
- android - 谷歌云服务的视频智能API是否可用于android?
- javascript - 如何动态填充三角二维数组?
- html - 如何用 SQL Server 中的数据填充 Select?使用 ASP 经典
- wicket - Apache Wicket 1.6 或更高版本不支持 visual-wicket
- selenium - 在 python 中运行 Geckodriver 时出错:[Errno 2] 没有这样的文件或目录:'geckodriver.log'
- android - 如何打开封闭的房间数据库
- java - 如何使用 protobuf 编译 java 特定枚举
- javascript - 如何在javascript上为烛台顶点图添加注释