c++ - 警告 C4800 : 'int' : forcing value to bool 'true' or 'false'

标签 c++ templates

我编写了一个模板函数,它以 int32、bool 和 int16 作为输入。 但是对于 bool,我收到了这个警告。任何想法,我该如何解决。

template<class T>
void GameControl::assignValues(char *gaff, T &output)
{
   output = T(atoi(gaff));
}

函数调用如下:

int32 intout;
assignValues("1234", intout);
bool boolout;
assignValues("1234", boolout);

任何人都可以告诉,如何摆脱警告?

编辑: 这有效,但不确定后果。我只是抑制了警告。

#pragma warning( push )
#pragma warning( disable : 4101)
// Your function
#pragma warning( pop )

最佳答案

您的第一项工作是将函数参数列表更改为 const char* gaff,因为标准 C++ 不允许将 const char[N] 衰减为字符*。具有讽刺意味的是,您的编译器没有发出诊断,而是提示可疑的转换!

至于那个警告,你可以强制问题

output = static_cast<T>(atoi(gaff));

然后大多数编译器会假定您知道自己在做什么。如果您仍然收到警告,则专门化 bool 案例的模板函数;总的来说,我认为我更喜欢的解决方案(除了关闭该特定功能的警告的务实方法):

template<>
void assignValues(const char *gaff, bool &output)
{
   output = atoi(gaff) != 0;
}

关于c++ - 警告 C4800 : 'int' : forcing value to bool 'true' or 'false' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48943932/

相关文章:

c++ - 将模板转换为任意类型时如何避免编译器错误

c++ - 类 Stack 的模板特化

c++ - 即使主窗口关闭,应用程序也不会退出

C++ 运算符重载调用析构函数

c++ - Win32 : Prevent folder modification?

python - 使用 mako 生成 Cisco 配置。是否可以在模板中使用 netaddr 模块(或任何模块)?

templates - EF4 : Get the linked column names from NavigationProperty of an EDMX

c++ - 可以使用模板按名称访问结构变量吗?

c++ - 如何一般地获取 ar 的所有 .o 文件

c++ - 如何使用 msvc10 和 ICU 编译 boost 1.54?