【发布时间】:2013-08-08 14:27:13
【问题描述】:
当我惊讶于以下代码完全有效并且完全按预期工作时,我试图了解有关联合及其有用性的更多信息:
template <class T>
union Foo
{
T a;
float b;
Foo(const T& value)
: a(value)
{
}
Foo(float f)
: b(f)
{
}
void bar()
{
}
~Foo()
{
}
};
int main(int argc, char* argv[])
{
Foo<int> foo1(12.0f);
Foo<int> foo2((int) 12);
foo1.bar();
foo2.bar();
int s = sizeof(foo1); // s = 4, correct
return 0;
}
直到现在,我都不知道用模板、构造函数、析构函数甚至成员函数声明联合是合法的。如果相关,我使用的是 Visual Studio 2012。
当我在互联网上搜索有关以这种方式使用联合的更多信息时,我一无所获。这是 C++ 的新特性,还是 MSVC 特有的特性?如果没有,我想了解更多关于联合的信息,特别是它们的示例,例如类(上图)。如果有人能指点我更详细地解释联合及其作为数据结构的用法,将不胜感激。
【问题讨论】:
-
2003 标准,9.5 工会,第 1 段
"... A union can have member functions (including constructors and destructors), but not virtual (10.3) functions. ..."所以不是新的。只是不常见。在模板方面,我找不到任何特殊的措辞,但我很确定在这方面它被视为class(同样structs没有特殊的措辞)。跨度>