c++ - 如何防止从 char 数组到 bool 的隐式转换

标签 c++ casting

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

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

由于类型转换,上述代码编译成功,即使在需要 bool 的地方传递了一个 char 数组。

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

我查看了 StackOverflow 上的以下相关问题,但它们并没有完全解决这个问题。 Preventing implicit conversion in C++ , Why does the compiler choose bool over string for implicit typecast of L""?

最佳答案

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

void setBar(const char*);

这将使它在链接时失败。不过,您仍然需要进行所有其他隐式转换 - 从任何指针到 bool、整数到 bool、 float 到 bool ...

另一种选择:

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

这样,如果您使用 bool 以外的任何其他方式调用它,您将收到关于它是私有(private)的错误。

关于c++ - 如何防止从 char 数组到 bool 的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18463937/

相关文章:

c++ - gcc - 如何使用地址 sanitizer

c++ - 将 vector < vector <Point>> x 变换为 vector <Point> y

c++ - 我怎样才能使 C++ 更喜欢匹配父类重载而不是模板?

将 void* 转换为二维数组

C : Parse Hex string to unsigned long

java - 将对象转换为 Java 中的自定义 DTO 列表

c++ - list::sort 在 msvc 中使用什么排序算法?

c++ - 可以通过 const 引用返回默认参数的值吗?

c++ - 为什么我们需要为指针放置 *

c# - 将通用对象集合传递给需要基类型集合的方法