【发布时间】:2019-11-02 15:03:35
【问题描述】:
我有一个要包装ostringstream 的类。我是这样处理的:
class Foo {
ostringstream os;
public:
template <typename T>
decltype(ostream() << T(), Foo)& operator <<(const T& param) {
os << param;
return *this;
}
}
我的意图是免费获得为ostream 定义的任何运算符。但我得到了编译错误:
错误 C2893:无法专门化函数模板
unknown-type &Foo::operator <<(const T &)
我使用decltype 是不是错了?
【问题讨论】:
-
您是否尝试使用
decltype(ostream() << T(), Foo)作为 SFINAE? -
有什么理由不使用
Foo&作为返回类型? -
@NathanOliver 我的意思是我没有定义替代...插入。
-
我会考虑为此创建一个派生自
std::streambuf的类型,以便您的Foo实际上可以是具有所有功能的std::ostream。 Boost.Iostreams 可以提供帮助。一篇有点老但是不错的文章:gabisoft.free.fr/articles/fltrsbf1.html -
这对没有默认 ctor 的 T 不起作用,您需要 std::declval。
标签: c++ templates operator-overloading wrapper ostream