c++ - 使用自定义特征和 bool 类型的 c++11 枚举时出现 clang 编译错误

标签 c++ c++11 compiler-errors clang

以下代码使用 g++ 可以正常编译,但使用 clang 会失败(我测试过的所有版本):

#include <iostream>

namespace has_insertion_operator_impl
{
    typedef char no;
    typedef char yes[2];

    struct any_t
    {
        template <typename T>
        any_t(const T&);
    };

    yes& testStreamable(std::ostream&);
    no   testStreamable(no);

    no operator<<(const std::ostream&, const any_t&);

    template <typename T>
    struct has_insertion_operator
    {
        static std::ostream& s;
        static const T& t;
        static const bool value = sizeof(testStreamable(s << t)) == sizeof(yes);
    };
} // namespace has_insertion_operator_impl

template <typename T>
struct has_insertion_operator : has_insertion_operator_impl::has_insertion_operator<T>
{};

enum A : bool {
    Yup = true,
    Nop = false,
};

template <typename T>
bool getTraitVal(const T&) { return has_insertion_operator<T>::value; }

int main() { std::cout << getTraitVal(A::Yup) << std::endl; }

错误(仅使用 clang!)是这样的:

prog.cc:24:59: error: use of overloaded operator '<<' is ambiguous (with operand types 'std::ostream' (aka 'basic_ostream<char>') and 'const A')
        static const bool value = sizeof(testStreamable(s << t)) == sizeof(yes);

我相信这是一个足够小的例子。以下是在线编译器的链接:

当我将枚举类型从 bool 更改为 int 时 - 错误消失。

那么为什么会发生这种情况呢?这最初是在使用doctest时发现的。和 Catch测试框架 - 这是 bug report为捕获。这可能是一个 clang bug 吗?

最佳答案

我知道它不能回答您的问题,但 clang 似乎对基础类型“bool”的枚举有问题。

我将您的示例进一步简化为:

#include <iostream>

enum A : bool {
    Yup = true,
    Nop = false,
};

int main() { 
    A t = Yup;
    std::cout << t;
}

在这里您已经可以感受到正在发生的事情:

prog.cc:10:15: error: use of overloaded operator '<<' is ambiguous (with operand types 'ostream' (aka 'basic_ostream<char>') and 'A')
    std::cout << t;
    ~~~~~~~~~ ^  ~
/usr/local/libcxx-3.8/include/c++/v1/ostream:195:20: note: candidate function
    basic_ostream& operator<<(bool __n);
                   ^
/usr/local/libcxx-3.8/include/c++/v1/ostream:198:20: note: candidate function
    basic_ostream& operator<<(int __n);
                   ^
...

关于c++ - 使用自定义特征和 bool 类型的 c++11 枚举时出现 clang 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40503986/

相关文章:

c++ - 与 32 位和 64 位应用程序相同源的条件编译

c++ - 第一个元素之间的差异小于或等于第二个元素的最小值的对数对

gcc - 如何将-std = c99传递给g++?

c++ - 调试 Qt 应用程序

具有结构的 C++ 映射

c++ - 为什么类持有可复制的引用?

c - 不是常量初始化元素?

java - 此 token 错误后将引发

c++ - 按值返回的函数的值类别是否总是 xvalue?

c++ - 使用 move::semantic 将大量 vector 合并为一个更大的 vector