I want to add a constructor that could allow a variable number of arguments. caller is a function that could call other functions with their arguments(something simliar to thread but for calling functions only). I already made it with a function template
template <class C,class ... _Args >
void caller(C(*f) ( _Args ... __args ), _Args ... __args ){(*f ) ( __args ...) ;}
But I need to have a class because it also should make an object of this class. something like this.
caller()
I made a class for caller with a constractor that could call other functions with a known number of arguments.
#include <iostream>
class caller {
public:
caller(){std::cout<<"Constructor default"; }
caller(void (*Optype)(int),int a){Optype(a);std::cout<<"Constructor 1"; }
//*** Constructor for variable number of arguments**
};
and it works correctly with following code
#include <iostream>
#include "caller"
using namespace std;
void foo(int a){
cout<<a<<endl;
}
int main()
{
caller c;
caller();
caller(foo,2);
return 1;
}
I want to know how can I add a constructor which works with different numbers of variables and is it possible it allows different types of variables too? I ask for something like the function template that I already made but in the class.
CodePudding user response:
If you want a variadic list of arguments to the constructor you do this sort of thing:
#include <iostream>
struct Test
{
template<typename T>
Test(T i)
{
std::cout << "Test(T i) -> i=" << i << std::endl;
}
template<typename T, typename... R>
Test(T i, R... r)
: Test(r...)
{
std::cout << "Test(T i, R... r) -> i=" << i << std::endl;
}
};
int main()
{
Test a{1};
Test b{"A", 17};
Test c{18, 2.5f, "B"};
return 0;
}
CodePudding user response:
Thanks to @Treebeard answer I modified my code as below and it works.
using namespace std;
class thread {
public:
//default constructor
thread(){}
//other constructors
template<class C,typename... R>
thread(C(*f), R... r){
(*f ) ( r ...) ; } };
void foo(char a){
cout<<a<<endl;
}
void foo1(int a,int b , int c){
cout<<a b c<<endl;
}
int main()
{
thread t1;
thread();
thread(foo,'Z');
thread(foo1,2,3,100);
return 1;
}