以下代码使用 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/