C ++尝试使用模板输出函数显示不同类型的数据

时间:2018-03-31 17:23:02

标签: c++ templates

我已经创建了一个函数,它应该输出包含int,chars,字符串和一个名为item的类的数据类型。这是功能:

template < typename T >
void Output(const T* first, const T* last, char outforchar= '\0')
{
  if (outforchar== '\0')
  {
    std::for_each(first, last, [](T i){std::cout << i;});
  }
  else 
  {
    std::for_each(first, last, [outforchar](T i){std::cout << i << outforchar;});
  }
}

虽然此函数适用于int,chars和字符串等类型。它对于具有&gt;&gt;的项目类不起作用。操作员根据规格格式化输入。编译器抛出此错误:

./tempsorter.h:14:47: error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
     std::for_each(beg, end, [](T i){std::cout << i;});
                                               ^
In file included from /usr/include/c++/4.8.2/iostream:39:0,
                 from psort.cpp:16:
/usr/include/c++/4.8.2/ostream:602:5: error:   initializing argument 1 of ‘std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = Product]’
     operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)
     ^
In file included from /usr/include/c++/4.8.2/algorithm:62:0,
                 from ./tempsorter.h:2,
                 from psort.cpp:18:
/usr/include/c++/4.8.2/bits/stl_algo.h:4411:5: error: ‘_Funct std::for_each(_IIter, _IIter, _Funct) [with _IIter = const Item*; _Funct = Output(const T*, const T*, char) [with T = Item]::__lambda0]’, declared using local type ‘Output(const T*, const T*, char) [with T = Item]::__lambda0’, is used but never defined [-fpermissive]
     for_each(_InputIterator __first, _InputIterator __last, _Function __f)
     ^
/usr/include/c++/4.8.2/bits/stl_algo.h:4411:5: error: ‘_Funct std::for_each(_IIter, _IIter, _Funct) [with _IIter = const Item*; _Funct = Output(const T*, const T*, char) [with T = Item]::__lambda1]’, declared using local type ‘Output(const T*, const T*, char) [with T = Item]::__lambda1’, is used but never defined [-fpermissive]

我理解这个错误,可以使用类似的东西摆脱它:

for (auto i = first; i != last; ++i) 
{
  std::cout << i;
}

但是这会给我不正确的输出,所以我根本不能使用它。

我希望通过以下内容遍历各种类型:

for (typename E::ConsItr i = e.Begin(); i != e.End(); ++i)

我似乎无法理解如何将其实现到函数中,我做错了什么?

1 个答案:

答案 0 :(得分:2)

首先,

[](T const& i){std::cout << i;}

可能更好。此外,您可能错误地写了<<运算符。

std::ostream& operator<<(std::ostream& os, const SomeType& x)

它看起来应该是这样,并且可能是您的类型的朋友。确保它与您的类型位于同一名称空间中。或者您覆盖>>而不是<<