如何防止使用多种整数类型的boost::变体类型的隐式转换
How do I prevent implict conversion to boost::variant types with multiple types of integers?
我正在尝试使用boost::variant,并且我使用它的方式遇到了一些问题。我希望有人能解释一下这个情况。
我创建了一个boost::变体,并使用int
和unsigned int
对其进行模板化。当我赋值一个数值时,4)对于变体,我希望编译器抱怨,因为普通的旧4不能明确地推断它的类型。这是怎么编译的?编译器如何选择类型?
是否有一种方法可以让编译器抱怨这些事情?
#include <stdint.h>
#include <boost/variant.hpp>
#include <boost/scoped_ptr.hpp>
#include <cxxabi.h>
struct MyComplexType
{
int myInt;
uint32_t myUint;
};
int main()
{
boost::variant< MyComplexType, int, uint32_t, float, std::string> myAmbiguousVar;
myAmbiguousVar = 4; // <- ?? My compiler chooses this to be an int
int status;
boost::scoped_ptr<char> pDemangled(__cxxabiv1::__cxa_demangle(myAmbiguousVar.type().name(), 0, 0, &status));
std::cout << std::string(pDemangled.get()) << std::endl;
}
数字字面值的类型没有二义性,并且在很大程度上是隐式可转换的。简而言之,4
为int
, 4U
为unsigned int
。除非你的编译器对这类事情有一个特别的警告,否则你不太可能让它发出警告。
根据Michael Urman的回答,我想更完整地填写这个答案。
c++标准声明如下(2.14.2.2):
整数字面值的类型是表6中对应列表中第一个可以表示其值的类型。
表6列出了整数字面值的大致顺序:int、unsigned int、long int、unsigned long int、…等
基于以上,这就是为什么编译器将boost::variant赋值为int类型。
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++中的双指针类型转换
- 逐位操作的隐式类型转换
- 模板中的类型转换
- 在 C++(和 C)中进行类型转换时明显不一致
- 字符类型转换不兼容
- 将复杂的非基元C++数据类型转换为 Erlang/Elixir 格式,以使用 NIF 导出方法
- C++:用户定义的显式类型转换函数错误
- 将类指针类型转换为键时出错
- 通过引用传递参数时C++类型转换
- 在 C++ 中将一个模板类型的对象类型转换为另一个模板类型
- C++显式类型转换(C 样式强制转换)的强制表示法和static_cast的多种解释
- C++无效的函数类型转换
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 如何将Windows产品类型转换为名称?
- 通过构造函数方法输出的类到类类型转换是 5500 为什么不是 5555
- 事件系统:使用类型转换或联合进行继承
- 如何在参数中定义隐式类型转换的构造函数?
- 类模板实例化中的类型转换