【发布时间】:2020-04-01 11:49:42
【问题描述】:
我在 S.O 上关注了一个关于如何实现 Outputtable trait 类以在编译时检查是否可以在 std::ostream 上输出类型的线程。该类的实现如下:
template<typename U>
struct OstreamOutputableTrait
{
template<typename T>
static decltype(std::declval<std::ostream&>() << std::declval<T>(), std::true_type{} )
IsOstreamOutputtable(std::ostream& os, const T& var) {}
// for vector<T>
template<typename T>
static std::false_type IsOstreamOutputtable(std::ostream& os, const std::vector<T>& var)
{}
template<typename > static auto IsOstreamOutputtable(...) {
return std::false_type {};
}
static const auto value =
decltype(IsOstreamOutputtable(std::declval<std::ostream&>(), std::declval<U>()))::value;
};
// operator implementation
template<typename Key, typename T>
std::ostream& operatorImpl(std::ostream& os, const std::map<Key,T>& map, const std::true_type& ) {
for(auto it = map.begin(); it!= map.end(); ++it)
os << "(" << (*it).first << " ; " << (*it).second << ")" <<"\n";
return os;
}
template<typename Key, typename T>
std::ostream& operatorImpl(std::ostream& os, const std::map<Key, T>& map, const std::false_type& ) {
os << "\nElements of the map are not printable.\n";
return os;
}
// operator << on <Key, value> maps
template<typename Key, typename T>
std::ostream& operator<<(std::ostream& os, const std::map<Key, T>& map)
{
// redirect using SFINAE to correct Impl of the operator<< : ty always returns true!
auto ty = std::integral_constant<bool,
OstreamOutputableTrait<typename std::decay_t<T> >::value &&
OstreamOutputableTrait<typename std::decay_t<Key> >::value>();
operatorImpl(os, map, ty);
return os;
}
我遇到的问题是上面函数中的变量ty 总是返回std::true_type。这是否意味着std::map 模板类的<Key,T> 类型名在STL 中默认可以在std::ostream 上输出?如果有人能解释我可能做错了什么,那将对我有很大帮助。
谢谢 胺
【问题讨论】: