gpt4 book ai didi

c++ - 打印对象的文本表示

转载 作者:太空狗 更新时间:2023-10-29 21:19:42 27 4
gpt4 key购买 nike

我是 C++ 的新手。如果不正确,请原谅我的术语。我试着四处寻找我的问题的答案,但找不到(可能是因为我无法正确表达我的问题)。如果有人能帮助我,我将不胜感激。

我正在尝试编写一个类来创建可能包含对象或 native 类型的文本表示的字符串。本质上,我有

private:
stringstream ss;


public:
template< typename T >
Message& operator<<( const T& value ) {
ss << value;
return *this;
}

重载的 << 运算符获取一些值并尝试将其流式传输到字符串流中。如果 T,我认为我的编译器没问题类似于 int或者如果类 T定义方法 operator std::string() .但是,如果 T是某种类型,例如 vector<int> , 然后它不再有效因为 vector<int>没有定义 operator std::string() .

我是否可以重载这个运算符,这样如果 T定义 operator std::string() , 然后我打印文本表示,如果没有,我只打印它的地址?

谢谢。

最佳答案

这可以通过构建 has_insertion_operator 来实现此处描述的类型特征:https://stackoverflow.com/a/5771273/4323

namespace has_insertion_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_insertion_operator {
static std::ostream &s;
static T const &t;
static bool const value = sizeof( test(s << t) ) == sizeof( yes );
};
}

template<typename T>
struct has_insertion_operator :
has_insertion_operator_impl::has_insertion_operator<T> {
};

一旦我们有了这些,剩下的就相对简单了:

class Message
{
std::ostringstream ss;

public:
template< typename T >
typename std::enable_if<has_insertion_operator<T>::value, Message&>::type
operator<<( const T& value ) {
ss << value;
return *this;
}

template< typename T >
typename std::enable_if<!has_insertion_operator<T>::value, Message&>::type
operator<<( const T& value ) {
ss << &value;
return *this;
}
};

也就是说,如果定义了插入运算符,则打印值,否则打印其地址。

这不依赖于转换为- std::string运算符被定义——你只需要确保你的 T使用 operator << 可以“打印”实例(通常在定义每个 T 的相同范围内实现,例如命名空间或全局范围)。

关于c++ - 打印对象的文本表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26458177/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com