user3472
user3472

Reputation: 303

c++ forward variadac function arguments to a class constructor

In C++, is there a way to define a function that takes N number of random arguments (number and parameter types could be anything) and in that function, instantiates a class who's constructor expects those arguments. In pseudo-code, something like:

class ClassType {
   ClassType(int, string){}
};

void func(Args ...) {
  ClassType A(Args);
}

And better yet, define a function pointer for "func"

Upvotes: 0

Views: 100

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122585

Yes it is possible. Output of this

#include <iostream>
#include <utility>

struct ClassType {
   ClassType(int a, std::string b){
       std::cout << a << b;
   }
};

template <typename...Args>
void func(Args&& ... args) {
  ClassType A(std::forward<Args>(args)...);
}

int main() {
    func(12,std::string("foo"));
}

is

12foo

However, it isnt quite clear why you want func to be variadic when ClassTypes constructor only accepts int,string. Calling func with any other combination will fail.

And better yet, define a function pointer for "func"

You cannot have a function pointer to a template (you also cannot have a function pointer to a whole set of overloads). Thats not how function pointers work. What you can do is taking a function pointer to one particular instantiation of func:

auto fptr = &func<int,std::string>;

If you need some function like object that you can pass around then you can use a generic lambda instead of a bare function pointer (since C++17 I believe):

auto flamb = [](auto&&...args){ func(std::forward<decltype(args)>(args)...); };

This works because the lambda is of some type (albeit unnamed and unspecified) and only its operator() is templated. Hence you can pass such lambda around and only when actually calling it the respective operator() is instantiated. Though, also with that you can only call it with the right parameters (int and std::string).

Upvotes: 1

Related Questions