c ++ 11中模板化的联合

Jas*_*oss 10 c++ templates unions c++11

c ++ 11标准是否有关于模板化联合的说法?(我在http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf中找不到任何内容,但我没有仔细阅读.)

我有

template<typename T>
union u {
  T a;
  char b;
};

template<typename T>
u<T> make_u(T t) {
  return { .a = t };
}

int main() {
  return make_u<int>(1).a;
}
Run Code Online (Sandbox Code Playgroud)

此代码会导致icpc -std=c++11error: a designator into a template-dependent type is not allowed,g++ -std=c++0xerror: expected primary-expression before ‘.’ token,和g++ -std=c++11(版本4.8.0(实验))的说法internal compiler error: in lookup_field_1, at cp/search.c:387.我可以通过更换得到解决这个{ .a = t }t.但是,对于不是联盟第一个成员的字段,我不能这样做.有没有办法在模板化联合中选择除第一个成员之外的某个成员,其中相关成员是模板依赖的?(当然,我可以在堆栈上声明一个联合,并将该成员设置为我想要的值.但我无法在初始化列表或constexpr函数中执行此操作.)

ybu*_*ill 13

{ .a = t }语法是非标准GNU扩展,因此它与其他C++特性相互作用是C++标准的范围之外.

解决方案:编写标准C++:

u<T> make_u(T t) {
  u<T> r;
  r.a = t;
  return r;
}
Run Code Online (Sandbox Code Playgroud)

编辑:AFAIK,在C++ 11中,你可以为你的联盟提供一个构造函数(如果你愿意,还可以使用constexpr)来完成你需要的初始化.示例:http://ideone.com/s4GHjU