如何防止使用多种整数类型的boost::变体类型的隐式转换

How do I prevent implict conversion to boost::variant types with multiple types of integers?

本文关键字:类型 转换 何防止 boost 整数      更新时间:2023-10-16

我正在尝试使用boost::variant,并且我使用它的方式遇到了一些问题。我希望有人能解释一下这个情况。

我创建了一个boost::变体,并使用intunsigned 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;
}

数字字面值的类型没有二义性,并且在很大程度上是隐式可转换的。简而言之,4int, 4Uunsigned int。除非你的编译器对这类事情有一个特别的警告,否则你不太可能让它发出警告。

根据Michael Urman的回答,我想更完整地填写这个答案。

c++标准声明如下(2.14.2.2):

整数字面值的类型是表6中对应列表中第一个可以表示其值的类型。

表6列出了整数字面值的大致顺序:int、unsigned int、long int、unsigned long int、…等

基于以上,这就是为什么编译器将boost::variant赋值为int类型。