为什么显式运算符bool让我转换为任何原始类型?

时间:2013-11-20 01:14:38

标签: c++ visual-studio-2012 c++11 implicit-conversion

struct test
{
    explicit operator bool() const { return true; }
};

int main()
{
    test a;
    float b = static_cast<float>(a); // b = 1
}

允许这是正确的,还是VS错误?如果它符合设计,那么这里的最佳做法是什么?应该/我能做什么来阻止这种情况吗?

2 个答案:

答案 0 :(得分:3)

这看起来像一个VS错误:显式运算符不应该在强制转换中应用于bool以外的类型。

无法在C++11 modeC++98 mode中使用gcc进行编译。

  

我能做些什么来阻止这种情况吗?

你已经做了你需要做的事 - 这是编译器的问题。

答案 1 :(得分:3)

添加常规= delete转换应该有助于编译器实现其方式的错误:

struct test
{
    explicit operator bool() const { return true; }
    template<typename T> explicit operator T() const = delete;
};

on Coliru(没有MSVC :))

int main()
{
    test a;
    float b = static_cast<bool>(a);  // b = 1
    float c = static_cast<float>(a); // c = ?
}