以下代码在使用g++或clang++编译时会产生截然不同的结果。对不起,这个例子很长,但我无法让它更短。
程序应将特定位位置分配给特定类型,然后构建std::bitset
包含多个类型位。
#include <bitset>
#include <iostream>
using namespace std;
using Bts = bitset<32>;
int getNextId() { static int last{0}; return last++; }
template<class T> struct IdStore{ static const int bitIdx; };
template<class T> const int IdStore<T>::bitIdx{getNextId()};
template<class T> void buildBtsHelper(Bts& mBts) {
mBts[IdStore<T>::bitIdx] = true;
}
template<class T1, class T2, class... A>
void buildBtsHelper(Bts& mBts) {
buildBtsHelper<T1>(mBts); buildBtsHelper<T2, A...>(mBts);
}
template<class... A> Bts getBuildBts() {
Bts result; buildBtsHelper<A...>(result); return result;
}
template<class... A> struct BtsStore{ static const Bts bts; };
template<class... A> const Bts BtsStore<A...>::bts{getBuildBts<A...>()};
template<> const Bts BtsStore<>::bts{};
template<class... A> const Bts& getBtsStore() {
return BtsStore<A...>::bts;
}
struct Type1 { int k; };
struct Type2 { float f; };
struct Type3 { double z; };
struct Type4 { };
int main()
{
cout << getBtsStore<Type1, Type2, Type3, Type4>() << endl;
return 0;
}
- g++ 4.8.2打印-----:
00000000000000000000000000000001
- clang++ SVN打印:(
00000000000000000000000000001111
如预期的那样)
只有编译标志是-std=c++11
.
怎么了?我是否引入了未定义的行为?g++错了吗?