gpt4 book ai didi

c++ - 如何防止隐式转换为具有多种整数类型的 boost::variant 类型?

转载 作者:行者123 更新时间:2023-11-30 04:04:35 25 4
gpt4 key购买 nike

我正在尝试使用 boost::variant,但在使用它的方式上遇到了一些问题。我希望有人能对这种情况有所了解。

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

最佳答案

数字文字的类型是 not ambiguous , 并且在很大程度上是隐式可转换的。简而言之,4 是一个int4U 是一个unsigned int。除非您的编译器对此类事情有特定的警告,否则您不太可能让它发出警告。

关于c++ - 如何防止隐式转换为具有多种整数类型的 boost::variant 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23687534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com