如何防止从char数组隐式转换为bool [英] How to prevent implicit conversion from char array to bool

查看:885
本文介绍了如何防止从char数组隐式转换为bool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct Foo {
  void setBar(bool bar_) { bar = bar_; }
  bool bar;
};

int main() {
  Foo f;
  f.setBar("true");
}

上述代码由于类型转换而成功编译,即使char数组通过 bool

The above code compiles successfully due to type conversion, even though a char array is passed where a bool is expected.

是否可能导致此代码编译失败? (C ++ 03解决方案首选,因为我的工作场所的编译器是古老的。)

Is it possible to cause this code to fail compilation? (C++03 solution preferred, since the compiler at my workplace is ancient.)

我看了下面的相关问题在StackOverflow,但他们不是解决这个问题。 防止C ++中的隐式转换

I have looked at the following related questions on StackOverflow, but they don't quite address this problem. Preventing implicit conversion in C++, Why does the compiler choose bool over string for implicit typecast of L""?

推荐答案

您可以声明一个函数 const char * 并且不提供定义:

You can declare a function that takes const char* and don't provide a definition:

void setBar(const char*);

这将使其在链接时失败。你还剩下所有其他隐式转换,从任何指针到bool,积分到bool,浮动到bool ...

This will make it fail at link time. You're still left will all other implicit conversion, though - from any pointer to bool, integral to bool, floats to bool...

另一个选项:

struct Foo {
  void setBar(bool bar_) {}
private:
  template<typename T>
  void setBar(T bar) {}
};

这样,如果你使用 bool

这篇关于如何防止从char数组隐式转换为bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆