运算符<<() 失败时回退到 to_string()
Fallback to to_string() when operator<<() fails
我见过具有相应to_string()
函数的类型,但没有重载operator<<()
。因此,在插入流时,必须<< to_string(x)
冗长。我想知道是否可以编写一个通用函数,如果支持,用户operator<<()
,如果没有,则回退到<< to_string()
。
SFINAE 是矫枉过正的,请使用 ADL。
诀窍是确保operator<<
可用,而不一定是类型定义提供的:
namespace helper {
template<typename T> std::ostream& operator<<(std::ostream& os, T const& t)
{
return os << to_string(t);
}
}
using helper::operator<<;
std::cout << myFoo;
此技巧通常用于需要在std::swap<T>
和专用Foo::swap(Foo::Bar&, Foo::Bar&)
之间进行选择的通用代码中。
尝试
template <typename T>
void print_out(T t) {
print_out_impl(std::cout, t, 0);
}
template <typename OS, typename T>
void print_out_impl(OS& o, T t,
typename std::decay<decltype(
std::declval<OS&>() << std::declval<T>()
)>::type*) {
o << t;
}
template <typename OS, typename T>
void print_out_impl(OS& o, T t, ...) {
o << t.to_string();
}
住
是的,这是可能的。
#include <iostream>
#include <sstream>
#include <string>
#include <type_traits>
struct streamy
{
};
std::ostream&
operator<<(std::ostream& os, const streamy& obj)
{
return os << "streamy [" << static_cast<const void *>(&obj) << "]";
}
struct stringy
{
};
std::string
to_string(const stringy& obj)
{
auto oss = std::ostringstream {};
oss << "stringy [" << static_cast<const void *>(&obj) << "]";
return oss.str();
}
template <typename T>
std::enable_if_t
<
std::is_same
<
std::string,
decltype(to_string(std::declval<const T&>()))
>::value,
std::ostream
>&
operator<<(std::ostream& os, const T& obj)
{
return os << to_string(obj);
}
int
main()
{
std::cout << streamy {} << 'n';
std::cout << stringy {} << 'n';
}
仅当表达式 to_string(obj)
类型正确以obj
const T&
并且具有 std::string
类型的结果时,泛型operator<<
才可用。正如您在评论中已经猜想的那样,这确实是 SFINAE 在起作用。如果decltype
表达式格式不正确,我们将得到替换失败,重载将消失。
但是,这可能会让您遇到模棱两可的重载。至少,将回退operator<<
放入其自己的namespace
中,并且仅在需要时通过using
声明将其拖入本地。我认为你最好写一个做同样事情的命名函数。
namespace detail
{
enum class out_methods { directly, to_string, member_str, not_at_all };
template <out_methods> struct tag {};
template <typename T>
void
out(std::ostream& os, const T& arg, const tag<out_methods::directly>)
{
os << arg;
}
template <typename T>
void
out(std::ostream& os, const T& arg, const tag<out_methods::to_string>)
{
os << to_string(arg);
}
template <typename T>
void
out(std::ostream& os, const T& arg, const tag<out_methods::member_str>)
{
os << arg.str();
}
template <typename T>
void
out(std::ostream&, const T&, const tag<out_methods::not_at_all>)
{
// This function will never be called but we provide it anyway such that
// we get better error messages.
throw std::logic_error {};
}
template <typename T, typename = void>
struct can_directly : std::false_type {};
template <typename T>
struct can_directly
<
T,
decltype((void) (std::declval<std::ostream&>() << std::declval<const T&>()))
> : std::true_type {};
template <typename T, typename = void>
struct can_to_string : std::false_type {};
template <typename T>
struct can_to_string
<
T,
decltype((void) (std::declval<std::ostream&>() << to_string(std::declval<const T&>())))
> : std::true_type {};
template <typename T, typename = void>
struct can_member_str : std::false_type {};
template <typename T>
struct can_member_str
<
T,
decltype((void) (std::declval<std::ostream&>() << std::declval<const T&>().str()))
> : std::true_type {};
template <typename T>
constexpr out_methods
decide_how() noexcept
{
if (can_directly<T>::value)
return out_methods::directly;
else if (can_to_string<T>::value)
return out_methods::to_string;
else if (can_member_str<T>::value)
return out_methods::member_str;
else
return out_methods::not_at_all;
}
template <typename T>
void
out(std::ostream& os, const T& arg)
{
constexpr auto how = decide_how<T>();
static_assert(how != out_methods::not_at_all, "cannot format type");
out(os, arg, tag<how> {});
}
}
template <typename... Ts>
void
out(std::ostream& os, const Ts&... args)
{
const int dummy[] = {0, ((void) detail::out(os, args), 0)...};
(void) dummy;
}
然后像这样使用它。
int
main()
{
std::ostringstream nl {"n"}; // has `str` member
out(std::cout, streamy {}, nl, stringy {}, 'n');
}
函数decide_how
使您可以完全灵活地决定如何输出给定类型,即使有多个选项可用。它也很容易扩展。例如,某些类型具有 str
成员函数,而不是 ADL 可查找to_string
自由函数。(实际上,我已经这样做了。
该函数detail::out
使用标记调度来选择适当的输出方法。
can_HOW
谓词是使用我认为非常优雅的void_t
技巧实现的。
可变参数out
函数使用"对于每个参数"技巧,我觉得这更优雅。
请注意,代码为 C++14,需要最新的编译器。
根据@MSalters的答案(功劳归他),这个解决了我的问题,应该会做出一个完整的答案。
#include <iostream>
#include <string>
#include <type_traits>
struct foo_t {};
std::string to_string(foo_t) {
return "foo_t";
}
template <class CharT, class Traits, class T>
typename std::enable_if<std::is_same<CharT, char>::value,
std::basic_ostream<CharT, Traits>&>::type
operator<<(std::basic_ostream<CharT, Traits>& os, const T& x) {
return os << to_string(x);
}
int main() {
std::cout << std::string{"123"} << std::endl;
std::cout << foo_t{} << std::endl;
}
- "error: no matching function for call to"构造函数错误
- 调用专用模板时出错"no matching function for call to [...]"
- C++ Singleton - Prevent ::instance() to variable
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- Visual Studio Code "undefined reference to `WinMain@16'"
- 使用 GCC 卸载的 OpenMP 卸载失败,并出现"Ptx assembly aborted due to errors"
- 如何解决"invalid conversion from 'char' to 'const char*'"
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 使用 MATLAB 编码器生成C++代码:编译错误"undefined reference to `rgb2gray_tbb_real64'"
- <<操作员在下面的行中工作
- 尝试链接我的着色器时,我收到错误代码"error c5145 must write to gl_position"
- Python str to C++ to Python str
- 为什么创建友元类的实例会导致"undefined reference to"错误?
- System.InvalidCastException - SQL to C++ - safe_cast<float>
- 使用 cmake 的 Linux 终端上的"Conversion to non-scalar type is requested"错误
- "no matching function for call to 'Vector::Vector'"错误
- vector<vector<double>> to mxArray using memcpy
- Tensorflow c++ api undefined reference to 'tflite::D efaultErrorReporter()'