gpt4 book ai didi

c++ - c++11 中的模板化 union

转载 作者:可可西里 更新时间:2023-11-01 15:53:43 26 4
gpt4 key购买 nike

c++11 标准对模板化 union 有什么规定吗? (我在 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;
}

此代码导致 icpc -std=c++11error: a designator into a template-dependent type is not allowed, g++ -std =c++0x 表示 error: expected primary-expression before '.' tokeng++ -std=c++11(版本 4.8. 0(实验))表示 内部编译器错误:在 lookup_field_1 中,位于 cp/search.c:387。我可以通过将 { .a = t } 替换为 t 来解决这个问题。但是,对于不是 union 会第一个成员的字段,我无法执行此操作。有没有办法在模板 union 中选择除第一个成员以外的其他成员,相关成员依赖于模板? (当然,我可以在堆栈上声明一个 union ,并将成员设置为我想要的值。但我不能在初始化列表或 constexpr 函数中这样做。)

最佳答案

{ .a = t } 语法是非标准的 GNU 扩展,因此它与其他 C++ 功能的交互超出了 C++ 标准的范围。

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

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

编辑:据我所知,在 C++11 中,您可以为您的 union 提供一个构造函数(如果您愿意,可以是一个 constexpr)来执行您需要的初始化。示例:http://ideone.com/s4GHjU

关于c++ - c++11 中的模板化 union ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13432419/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com