【发布时间】:2016-03-22 22:11:23
【问题描述】:
我正在使用C++03 method to detect the presence of a function at compile time。即使我使用的是 C++14,我也必须使用这种方法而不是 void_t 方法,因为我必须支持 GCC 4.9,并且在使用 void_t 方法时会出错(奇怪的是只有 Ubuntu 14 的 GCC 4.9 有这个问题,而不是 Fedora 的,但在 GCC5+ AFAICT 中已全面修复)。
具体来说,我正在检查operator<<(std::ostream&, const T&) 的存在,这样我就可以拥有一个可以接受任何类型的漂亮打印函数。当函数被调用时,如果类型支持它,您将获得常规的 ostream 输出,并且当未定义运算符时,您会收到一条关于没有实现的回退消息。代码在底部。
到目前为止,这对我来说效果很好,直到我遇到了由 3rd 方库定义的我无法更改的类型。该类型具有对 bool 和 float 的隐式转换运算符。这意味着当 SFINAE 检查完成以查看 s << t 是否有效时,我会收到编译器错误,因为 s << t 不明确。在这种情况下,我希望它只报告没有像正常的实现,而不是尝试选择隐式转换。有没有办法改变 SFINAE 检查以使这成为可能?我已经检查过,GCC5 的 void_t 方法似乎可以满足我的要求(在下面的代码中注释掉),但由于上述原因,我还不能使用它。
测试用例:
#include <iostream>
#include <typeinfo>
#include <type_traits>
namespace detail {
namespace has_ostream_operator_impl {
typedef char no;
typedef char yes[2];
struct any_t {
template<typename T> any_t( T const& );
};
no operator<<( std::ostream const&, any_t const& );
yes& test( std::ostream& );
no test( no );
template<typename T>
struct has_ostream_operator {
static std::ostream &s;
static T const &t;
// compiler complains that test(s << t) is ambiguous
// for Foo
static bool const value = sizeof( test(s << T(t)) ) == sizeof( yes );
};
}
template<typename T>
struct has_ostream_operator :
has_ostream_operator_impl::has_ostream_operator<T> {
};
// template<class, class = std::void_t<>>
// struct has_ostream_operator : std::false_type {};
// template<class T>
// struct has_ostream_operator<
// T,
// std::void_t<
// decltype(std::declval<std::ostream&>() << std::declval<const T&>())>>
// : std::true_type {};
}
template<class X>
std::enable_if_t<
detail::has_ostream_operator<X>::value
&& !std::is_pointer<X>::value>
prettyPrint(std::ostream& o, const X& x)
{
o << x;
}
template<class X>
std::enable_if_t<
!detail::has_ostream_operator<X>::value
&& !std::is_pointer<X>::value>
prettyPrint(std::ostream& o, const X& x)
{
o << typeid(x).name()
<< " (no ostream operator<< implementation)";
}
template<class X>
void prettyPrint(std::ostream& o, const X* x)
{
o << "*{";
if(x) {
prettyPrint(o, *x);
} else {
o << "NULL";
}
o << "}";
}
struct Foo {
operator float() const {
return 0;
}
operator bool() const {
return false;
}
};
struct Bar {};
int main()
{
Bar x;
Foo y;
prettyPrint(std::cout, 6); // works fine
std::cout << std::endl;
prettyPrint(std::cout, Bar()); // works fine
std::cout << std::endl;
prettyPrint(std::cout, x); // works fine
std::cout << std::endl;
prettyPrint(std::cout, &x); // works fine
std::cout << std::endl;
// prettyPrint(std::cout, y); // compiler error
std::cout << std::endl;
return 0;
}
【问题讨论】:
-
对于 GCC the following workaround
-
void_t/CWG1558 问题很容易解决。 -
@PiotrSkotnicki 哦,太好了,我没有意识到这一点。在下面做一个答案,我会接受。虽然我有点想知道为什么 void_t 版本没有这个问题。它仍然调用运算符... declval 的返回类型由于某种原因不能隐式转换?
-
@JosephGarvin 解释了here
-
@PiotrSkotnicki 这解释了为什么 void_t 的解决方法使它在 GCC 4.9 中工作,但我问为什么 void_t 在隐式转换使其不明确时不会出错,而原来的 has_ostream_operator 确实调用了哪个重载.事实上,如果它不考虑隐式转换,这意味着有时特征会出错。
标签: c++ c++11 gcc c++14 sfinae