【问题标题】:Can you pass a manipulator to a function?您可以将操纵器传递给函数吗?
【发布时间】:2013-01-20 02:10:16
【问题描述】:

我想将操纵器列表传递给函数,如下所示:

void print(const vector<std::smanip>& manips) {
  // ...
  for (auto m : manips)
    cout << m;
  // ...
}

理想情况下,它会被这样的代码调用:

some_object.print({std::fixed, std::setprecision(2)}));

g++ 4.7.0 说:

error: ‘std::smanip’ has not been declared

显然,smanip 并没有真正在标准中定义,C++11 编译器不需要为操纵器的类型提供明确的名称。我尝试通过从已知的操纵器中提取来声明类型,如下所示:

typedef decltype(std::fixed) manip;

这打开了许多新的错误消息,包括这个:

error: ‘const _Tp* __gnu_cxx::new_allocator< <template-parameter-1-1> 
>::address(__gnu_cxx::new_allocator< <template-parameter-1-1> >::const_reference)
const [with _Tp = std::ios_base&(std::ios_base&); __gnu_cxx::new_allocator<
<template-parameter-1-1> >::const_pointer = std::ios_base& (*)(std::ios_base&);
__gnu_cxx::new_allocator< <template-parameter-1-1> >::const_reference =
std::ios_base& (&)(std::ios_base&)]’ cannot be overloaded

我应该现在就放弃,还是有办法做到这一点?

【问题讨论】:

  • 操纵器通常是函数,因此它们没有通用的基类。
  • 你可以用一个流操作符定义你自己的包装类,它应用了操纵器和一个通用的基础,并将它用于你的参数?
  • 如果你真的想这样做,你可能需要把你的函数写成一个可变参数模板(因为不同的操纵器有不同的类型,其中大部分你不知道)。即使这样,它也不会是微不足道的(例如,您可能还需要使用 std::bind 来处理带参数的操纵器)。
  • @JerryCoffin 我相信可变参数函数模板也可以。
  • @Angew:我以为我就是这么说的。反正就是我想说的……

标签: c++ c++11 iostream iomanip


【解决方案1】:

输出操纵器只是为某些basic_ostream 实例化定义了os &lt;&lt; m 的任何类型。操纵器可以是一个函数(受basic_ostreamoperator&lt;&lt; 重载),但它也可以是定义了自己的operator&lt;&lt; 的任何类型。因此,我们需要执行类型擦除以捕获 operator&lt;&lt; 以获得适当的 basic_ostream 实例化;最简单的方法是使用 std::function 和 lambda:

#include <iostream>
#include <iomanip>
#include <functional>
#include <vector>

template<typename S>
struct out_manipulator: public std::function<S &(S &)> {
   template<typename T> out_manipulator(T &&t): std::function<S &(S &)>(
      [=](S &i) -> S &{ return i << t; }) {}
   template<typename T> out_manipulator(T *t): std::function<S &(S &)>(
      [=](S &i) -> S &{ return i << t; }) {}    // for g++
   template<typename U> friend U &operator<<(U &u, out_manipulator &a) {
      return static_cast<U &>(a(u));
   }
};

void print(const std::vector<out_manipulator<std::ostream>> &manips) {
   for (auto m: manips)
      std::cout << m;
}

int main() {
   print({std::fixed, std::setprecision(2)});
   std::cout << 3.14159;
}

【讨论】:

  • 有趣的方法,但不能用 g++-4.7 编译。
  • @OlafDietsche clang-3.2 很好;看起来像 g++ 处理对函数的通用引用的错误。我看看能不能找到解决办法。
  • @OlafDietsche 我为 g++ 添加了重载;它现在适用于 g++-4.7.2。
  • 谢谢!非常简单直接的方法。
【解决方案2】:

您的操纵器几乎可以有任意类型,因此您必须使用模板来处理它们。为了使用固定类型的指针或引用访问它们,您必须为所有这些模板使用公共基类。这种多态性仅适用于指针和引用,但您可能需要值语义,特别是用于将它们存储在包含中。所以最简单的方法是让shared_ptr 负责内存管理,并使用另一个类对用户隐藏所有丑陋的细节。

结果可能如下所示:

#include <memory>
#include <iostream>

// an abstract class to provide a common interface to all manipulators
class abstract_manip {
public:
  virtual ~abstract_manip() { }
  virtual void apply(std::ostream& out) const = 0;
};

// a wrapper template to let arbitrary manipulators follow that interface
template<typename M> class concrete_manip : public abstract_manip {
public:
  concrete_manip(const M& manip) : _manip(manip) { }
  void apply(std::ostream& out) const { out << _manip; }
private:
  M _manip;
};

// a class to hide the memory management required for polymorphism
class smanip {
public:
  template<typename M> smanip(const M& manip)
    : _manip(new concrete_manip<M>(manip)) { }
  template<typename R, typename A> smanip(R (&manip)(A))
    : _manip(new concrete_manip<R (*)(A)>(&manip)) { }
  void apply(std::ostream& out) const { _manip->apply(out); }
private:
  std::shared_ptr<abstract_manip> _manip;
};

inline std::ostream& operator<<(std::ostream& out, const smanip& manip) {
  manip.apply(out);
  return out;
}

这样,您的代码在对命名空间进行一些细微更改后即可工作:

void print(const std::vector<smanip>& manips) {
  for (auto m : manips)
    std::cout << m;
}

int main(int argc, const char** argv) {
  print({std::fixed, std::setprecision(2)});
}

【讨论】:

  • 我尝试了接受的答案和这个。这个效果更好,恕我直言:操纵器可以存储在向量中,操纵器的向量可以存储和传递。出于某种原因,接受的答案不允许这样做。
【解决方案3】:

由于操纵器是函数,它取决于它们的签名。这意味着,您可以创建具有相同签名的操纵器向量。

例如:

#include <iomanip>
#include <vector>
#include <iostream>

typedef std::ios_base& (*manipF)( std::ios_base& );

std::vector< manipF > getManipulators()
{
    std::vector< manipF > m =
    {
        std::showpos,
        std::boolalpha
    };
    return m;
}

int main()
{
  auto m = getManipulators();

  for ( auto& it : m )
  {
    std::cout<<it;
  }
  std::cout<<"hi " << true << 5.55555f << std::endl;
}

替代方法是使用 lambda:

#include <iomanip>
#include <vector>
#include <iostream>
#include <functional>

typedef std::function< std::ios_base& ( std::ios_base& ) > manipF;

std::vector< manipF > getManipulators()
{
    std::vector< manipF > m =
    {
        std::showpos,
        std::boolalpha,
        [] ( std::ios_base& )->std::ios_base&
        {
          std::cout << std::setprecision( 2 );
          return std::cout;
        }
    };
    return m;
}

int main()
{
  auto m = getManipulators();

  for ( auto& it : m )
  {
    it(std::cout);
  }
  std::cout<<"hi " << true << 5.55555f << std::endl;
}

【讨论】:

  • 您的 setprecision lambda 使用 std::cout,但不使用给定参数。我猜,这是因为setprecision 是根据basic_[io]stream 定义的。否则,我喜欢你的方法 +1
【解决方案4】:

标准 C++17 解决方案,可能基于 std::tuple。这是 P.O.C.

int main()
{
// quick p.o.c.
auto ios_mask_keeper = [&](auto mask) {
    // keep tuple here
    static auto mask_ = mask;
    return mask_;
};

// make required ios mask and keep it
auto the_tuple = ios_mask_keeper(
    // please note we can mix ios formaters and iomanip-ulators
    std::make_tuple(std::boolalpha, std::fixed, std::setprecision(2) ) 
);

// apply iomanip's stored in a tuple
std::apply([&](auto & ...x) 
{
    // c++17 fold 
    (std::cout << ... << x);
}, the_tuple);

return 0;

}

可以将元组保留在一个类中,等等。在 MSVC CL 编译器版本 19.14.26431.0 和使用 clang 的 obligatory Wand Box 中都可以使用。

【讨论】:

    猜你喜欢
    • 2017-09-17
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多