如何在C++ 17中打印一个模板以控制?
我有此基本模板类:
template<typename Type>
struct InputBase {
virtual void DisplaySingleResult(Type const& res) const {
std::cout << res << std::endl;
}
};
因此,下面的代码不会编译,因为 vector
没有&lt;&lt;&lt;
运算符
struct Input : InputBase<std::vector<std::vector<int>>> {
void DisplaySingleResult(std::vector<std::vector<int>> const& results) const override {
for (std::vector<int> const& result : results) {
std::cout << "[" << result[0] << "," << result[1] << "]";
}
std::cout << std::endl;
}
};
在编译时,方法 inputBase :: displaySingleresult
无法编译,因为它使用 vector
type。
解决方法是使虚拟 inputBase :: displaysingleresult
方法纯虚拟。
但是,我想在我的基类中具有 displaysingleresult
方法,并具有相同的签名,以避免重写所有其他派生的类。如何在C ++ 17中做到这一点?
解决方案试验: inputbase :: displaysingleresult ,检查模板类型是否具有&lt;&lt;&lt;
运算符。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不建议为
std :: Ostream&amp;提供超载。操作员&lt;&lt;(std :: ostream&amp;,const std :: vector&lt; t&gt;&amp;&amp;)
直接(不确定是否允许它)。但是间接。而不是调用
std :: Cout&lt;&lt; res&lt;&lt; std :: endl;
您可以调用一个函数:现在您可以为没有
运算符&lt;&lt;&lt;
提供超载要考虑制作
print_result
类模板而不是函数模板。例如,当t
具有begin> begin()
and end(end eend() end()。I do not recommend to provide an overload for
std::ostream& operator<<(std::ostream&,const std::vector<T>&)
directly (not sure if it is even allowed). But indirectly.Instead of calling
std::cout << res << std::endl;
you can call a function:Now you can provide overloads for any type that does not have a
operator<<
, egTo be more flexible with specializations you might want to consider to make
print_result
a class template rather than function template. For example there could be a specialization that callsprint_result
on the elements whenT
hasbegin()
andend()
.您可以在编译时测试是否适当支持类型:
std :: String
)。开始
和结束
函数使用这些功能。这可能如下:
递归调用该功能也允许打印嵌套容器(感谢对于提示):
请注意:
运算符&lt;&lt;
更喜欢C ++。std :: begin
和std :: end end
而不是使用。You could test at compile-time if the type is supported appropriately:
std::string
).begin
andend
functions use these.This might look as follows:
Recursively calling the function instead comes allows to print nested containers as well (thanks 463035818_is_not_a_number for the hint):
Note that:
static
asthis
is not used anywhere.operator<<
instead would be more C++ like.std::begin
andstd::end
instead.如果您需要具有
displaysingleresult()
是虚拟的,那么一种典型的方法是委派给非虚拟函数,这可以是模板:那么您可以templetize
displaysingleresultimpl()。现在,在许多情况下,您不想在基类(或只想提供典型的实现)中这样做 - 在这些情况下,CRTP想到:
CRTP是一个非常强大的工具,不要过度使用它。
If you need to have
DisplaySingleResult()
to be virtual, a typical way is to delegate to a non-virtual function, which can be a template:Then you can templetize
DisplaySingleResultImpl()
. Now, in many cases, you don't want to do that in the base class (or only want to provide a typical implementation) - in these cases, CRTP comes to mind:CRTP is a very powerful tool, don't overuse it.