Can union be templated?

房东的猫 提交于 2019-12-05 09:04:07

问题


It seems unions can be templated in c++11, they are used for example in the reference implementation of std::optional.

Was that possible before c++11 ?


回答1:


Yes, it seems that this has always been allowed. A union is a class, and a template is either a function or a class template.

Relevant parts of the standards:

  • [temp]

    The declaration in a template-declaration shall

    — declare or define a function or a class, [...]

  • [class]

    A union is a class defined with the class-key union

(So one might argue that the new type trait std::is_class is a slight misnomer; the traits are supposed to partition the space of types, and so is_union is a separate, mutually exclusive trait.)




回答2:


Yes, a particularly useful application is to represent a type simultaneously as a byte array:

template <typename T>
union test
{
    unsigned char ch[sizeof(T)];
    T variable;
};



回答3:


In place of a union you can also use std::variant as of c++17 https://en.cppreference.com/w/cpp/utility/variant



来源:https://stackoverflow.com/questions/20743582/can-union-be-templated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!