How to store arguments of variational type?

I want to call this function foo a member function, not a constructor. For this, I have to store the values ​​somewhere.
I cannot understand the syntax to do this.

#include <iostream>
void foo(int a, int b)
{
    std::cout<<a<<b;
}
template<typename... Args>
struct Foo
{
public:
    Foo(Args... args){foo(args...);}
    void action(){}
private:
    //Args... ?
};

int main()
{
    Foo<int,int> x(1,2);
}
+4
source share
1 answer

You can opt out of templating Foowith std::functionand std::bind:

#include <functional>
#include <iostream>

void foo(int a, int b)
{
  std::cout<<a<<b;
}

struct Foo
{
public:
  template<typename... Args>
  Foo(Args&&... args)
      // bind the arguments to foo
    : func_(std::bind(foo, std::forward<Args>(args)...)) { }

  // then you're able to call it later without knowing what was bound to what.
  void action(){ func_(); }

private:
  std::function<void()> func_;
};

int main()
{
  Foo x(1,2);

  x.action();
}

EDIT: to respond to the comment, to bind the constructor, I would use a function template like

template<typename T, typename... Args> T *make_new(Args&&... args) {
  return new T(std::forward<Args>(args)...);
}

and then

std::bind(make_new<SomeClass, Args...>, std::forward<Args>(args)...)

: std::make_shared std::make_unique ( ++ 14), .

+4

Source: https://habr.com/ru/post/1568665/


All Articles