草庐IT

c++ - 如何为模板方法实现编译时 foreach()?

coder 2024-02-21 原文

我想实现一个编译时的 foreach() ,它可以调用给定的模板成员函数 N 次。 目前我有我的编译时间foreach:

struct ForEach
{
   template <size_t Dummy>
   struct IntToType {};

   typedef IntToType<true> ForEachDoNotTerminateLoop;
   typedef IntToType<false> ForEachTerminateLoop;

   template <size_t TIdx, size_t TCount, typename TMethod>
   static void ForEachImpl(ForEachDoNotTerminateLoop, TMethod method)
   {
      method.Invoke<TIdx>();
      ForEachImpl<TIdx + 1, TCount, TMethod>(Internal::IntToType<(TIdx + 1 < TCount)>(), method);
   }

   template <size_t TIdx, size_t TCount, typename TMethod>
   static void ForEachImpl(ForEachTerminateLoop, TMethod method)
   {
   }

   template <size_t TCount, typename TMethod>
   static void Member(TMethod method)
   {
      ForEachImpl<0, TCount, TMethod>(Internal::IntToType<(0 < TCount)>(), method);
   }
};

还有一些模板类:

template <typename T, size_t TCount>
class SomeClass
{
public:
   void Foo(int arg1)
   {
      ForEach::Member<TCount>(BarInvoker(this, arg1));
   }

private:
   struct BarInvoker // <-- How can I make this invoker a template to make it more flexible?
   {
      BarInvoker(SomeClass* instance, int arg1)
         : instance(instance)
         , arg1(arg1)
      {}

      template <size_t N>
      void Invoke()
      {
         instance->Bar<N>(arg1);
      }

      int arg1;
      SomeClass* instance;
   };

   template <size_t N>
   void Bar(int arg1)
   {
      _data[N] = arg1;
   }

   int* _data;
   T* _otherData;
};

有没有办法绕过“调用者”仿函数,使其更灵活(模板)和更易于使用? 我真的不喜欢通过为我的每个私有(private)成员函数添加一个“调用程序” stub 来使我的代码膨胀。 最好调用ForEach::Member<TCount, int>(Bar, 5);

在此先感谢您帮助我解决这个模板问题! :)

最佳答案

将模板函数包装在一个类中并将该类的一个实例传递给 ForEach::Call<> 并使用任意参数调用它,这似乎是一个相当干净的解决方案。

ForEach::Call<>的电话看起来像:ForEach::Call<N>(function_object, arguments...)

function_object是一个具有 operator() 的类定义为:

template <std::size_t Idx>  // Current index in the for-loop.
void operator()(/* arguments... */) { /* Impl. */ }

这是我的 ForEach<> 版本。

class ForEach {
  public:

  /* Call function f with arguments args N times, passing the current index
     through the template argument. */
  template <std::size_t N, typename F, typename... Args>
  static void Call(F &&f, Args &&...args) {
    Impl<0, N>()(std::forward<F>(f), std::forward<Args>(args)...);
  }

  private:

  /* Forward declaration. */
  template <std::size_t Idx, std::size_t End>
  class Impl;

  /* Base case. We've incremeneted up to the end. */
  template <std::size_t End>
  class Impl<End, End> {
    public:

    template <typename F, typename... Args>
    void operator()(F &&, Args &&...) { /* Do nothing. */ }

  };  // Impl<End, End>

  /* Recursive case. Invoke the function with the arguments, while explicitly
     specifying the current index through the template argument. */
  template <std::size_t Idx, std::size_t End>
  class Impl {
    public:

    template <typename F, typename... Args>
    void operator()(F &&f, Args &&...args) {
      std::forward<F>(f).template operator()<Idx>(std::forward<Args>(args)...);
      Impl<Idx + 1, End>()(std::forward<F>(f), std::forward<Args>(args)...);
    }

  };  // Impl<Idx, End>

};  // ForEach

我写了一些类似于您的 SomeClass 的东西来演示它的用途。

template <std::size_t Size>
class Ints {
  public:

  using Data = std::array<int, Size>;

  /* Call Assign, Size times, with data_ and n as the arguments. */
  void AssignAll(int n) { ForEach::Call<Size>(Assign(), data_, n); }

  /* Call Print, Size times, with data_ and n as the arguments. */
  void PrintAll() const { ForEach::Call<Size>(Print(), data_); }

  private:

  /* Wraps our templated assign function so that we can pass them around. */
  class Assign {
    public:

    template <size_t N>
    void operator()(Data &data, int arg) const {
      data[N] = arg;
    }

  };  // Assign

  /* Wraps our templated print function so that we can pass them around. */    
  class Print {
    public:

    template <size_t N>
    void operator()(const Data &data) const {
      std::cout << data[N] << std::endl;
    }

  };  // Print

  /* Our data. */
  Data data_;

};  // Ints<Size>

Ints 类的简单用例。

int main() {
  Ints<5> ints;
  ints.AssignAll(101);
  ints.PrintAll();
}

打印:

101
101
101
101
101

关于c++ - 如何为模板方法实现编译时 foreach()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20131491/

有关c++ - 如何为模板方法实现编译时 foreach()?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  6. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  7. ruby - 如何为 emacs 安装 ruby​​-mode - 2

    我刚刚为fedora安装了emacs。我想用emacs编写ruby。为ruby​​提供代码提示、代码完成类型功能所需的工具、扩展是什么? 最佳答案 ruby-mode已经包含在Emacs23之后的版本中。不过,它也可以通过ELPA获得。您可能感兴趣的其他一些事情是集成RVM、feature-mode(Cucumber)、rspec-mode、ruby-electric、inf-ruby、rinari(用于Rails)等。这是我当前用于Ruby开发的Emacs配置:https://github.com/citizen428/emacs

  8. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  9. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  10. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

随机推荐