【发布时间】:2015-05-29 13:54:17
【问题描述】:
这个问题在我之前的问题之后:Generic operator<< ostream C++ for stringifiable class 我想在其中实现一个通用的<<ostream 运算符,它适用于任何拥有to_str() 方法的类。
感谢answer,我已成功检查一个类是否实现了to_str() 方法并使用std::cout << stringify(a)。但是,我很难编写模板 ostream<< 运算符以使 std::cout << a 正常工作。
以下测试代码:
#include <iostream>
#include <sstream>
#include <string>
template<class ...> using void_t = void;
template<typename T, typename = void>
struct has_to_string
: std::false_type { };
template<typename T>
struct has_to_string<T,
void_t<decltype(std::declval<T>().to_str())>
>
: std::true_type { };
template<typename T> std::enable_if_t<has_to_string<T>::value, std::string>
stringify(T t) {
return t.to_str();
}
template<typename T> std::enable_if_t<!has_to_string<T>::value, std::string>
stringify(T t) {
return static_cast<std::ostringstream&>(std::ostringstream() << t).str();
}
// The following does not work
/*
template<typename T> std::enable_if_t<has_to_string<T>::value, std::ostream&>
operator<<(std::ostream& os, const T& t) {
os << t.to_str();
return os;
}
template<typename T> std::enable_if_t<!has_to_string<T>::value, std::ostream&>
operator<<(std::ostream& os, const T& t) {
os << t;
return os;
}
*/
struct A {
int a;
std::string to_str() const { return std::to_string(a); }
};
struct B {
std::string b;
std::string to_str() const { return b; }
};
int main() {
A a{3};
B b{"hello"};
std::cout << stringify(a) << stringify(b) << std::endl; // This works but I don't want to use stringify
// std::cout << a << b << std::endl; // I want this but it does not work
}
给出与原始问题相同的错误。我做错了什么?
【问题讨论】:
-
带有
!has_to_string<T>::value的版本会在os << t调用自身时产生无限递归。
标签: c++ templates c++11 ostream enable-if