在 C++0x 中创建静态类型变体
我想知道,是否可以在 C++0x 中创建静态类型变体(其行为类似于 auto):
variant<int, bool, std::string> v = 45;
当我们将 v 分配给 int 以外的值时,它不会编译:
v = true; //Compile error
到目前为止我还没有找到任何优雅的解决方案。
I am wondering, if it's possible in C++0x to create a statically typed variant, (that behaves like auto) :
variant<int, bool, std::string> v = 45;
When we assign v to a value other than int, it doesn't compile:
v = true; //Compile error
So far I haven't found any elegant solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
此代码在我的机器上使用 Boost.Variant 和 g++ 4.5 针对 C++98 和 C++0x 进行编译。您想自己实现变体类型吗?然后你可能会研究 Boost 的实现。
如果您想要/获取/上述行为,您可以这样做:
这应该与您所描述的完全等效。
以下实现了克林顿的建议:
您只需要
和
即可实现完美的转发和整数提升的正确行为。This code compiles on my machine with Boost.Variant and g++ 4.5 for both C++98 and C++0x. Do you want to implement a variant-type yourself? Then you might look into the Boost implementation.
In the case that you want to /get/ the above behaviour you could do it like this:
This should be quite equivalent to what you describe.
The following implements Clintons suggestion:
You only need
<memory>
and<type_traits>
for this and get perfect forwarding and correct behaviour for integer promotion.我想,这是不可能的。
对象创建后,其静态类型不包含任何与对象初始化相关的信息。没关系,初始化时使用int或bool,变量的类型是相同的:
赋值运算符只能在运行时分析内容,并在需要时抛出异常。
I think, this is not possible.
After object is created, its static type does not contain any information related with object initialization. Does not matter, int, or bool was used for initialization, type of the variable is the same:
Assignment operator may only analyze contents at runtime, and throw exception, if this is needed.
不,我认为你不能在编译时做到这一点。
您可以使用enable_if或类似的方法启用或禁用一组赋值运算符,但要针对每个类型,而不是每个实例。当在一个编译单元中编译 v = true 时,我们如何知道您在另一个编译单元中使用了什么构造函数?
No, I don't think you can do that at compile time.
You could enable or disable a set of assignment operators using enable_if or similar, but would be per type, not per instance. When compiling v = true in one compilation unit, how could we know there what constructor you used in another compilation unit?