【发布时间】:2017-06-19 22:11:43
【问题描述】:
我尝试实现一个 type_traits 能够检测一个类是否可以在指令的上下文中使用,例如:std::cout << my_class_instance;。
我的实现试图从 SFINAE 中受益,以检测函数 std::ostream& operator<<(std::ostream&, const MyClass&) 是否可用于该类。不幸的是,它在应该与 C++ 11 兼容的 g++-4.9 下失败。其他编译器没有抱怨,似乎生成了正确的代码:g++-5+、clang++-3.3+ 和 Visual Studio。
这是我目前尝试的实现:
#include <iostream>
#include <type_traits>
#include <vector>
template <class... Ts> using void_t = void;
template <class T, class = void> struct can_be_printed : std::false_type {};
template <class T> struct can_be_printed<T, void_t<decltype(std::cout << std::declval<T>())>> : std::true_type {};
static_assert(!can_be_printed<std::vector<int>>::value, "vector<int> cannot be printed");
static_assert(can_be_printed<int>::value, "int can be printed");
现场示例位于:https://godbolt.org/g/6xFSef。 如果您需要更多详细信息,请不要犹豫。
【问题讨论】:
标签: c++ c++11 sfinae ostream g++4.9