我想添加一個可以允許可變數量引數的建構式。caller 是一個可以使用引數呼叫其他函式的函式(類似于執行緒但僅用于呼叫函式)。我已經用函式模板做了
template <class C,class ... _Args >
void caller(C(*f) ( _Args ... __args ), _Args ... __args ){(*f ) ( __args ...) ;}
但是我需要一個類,因為它也應該是這個類的一個物件。像這樣的東西。
caller()
我為呼叫者創建了一個帶有建構式的類,該類可以使用已知數量的引數呼叫其他函式。
#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**
};
并且使用以下代碼可以正常作業
#include <iostream>
#include "caller"
using namespace std;
void foo(int a){
cout<<a<<endl;
}
int main()
{
caller c;
caller();
caller(foo,2);
return 1;
}
我想知道如何添加一個可以處理不同數量變數的建構式,它是否也可能允許不同型別的變數?我要求像我已經制作的函式模板之類的東西,但在課堂上。
uj5u.com熱心網友回復:
如果您想要建構式的可變引數串列,您可以執行以下操作:
#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;
}
uj5u.com熱心網友回復:
感謝@Treebeard 的回答,我修改了我的代碼如下,它可以作業。
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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/339716.html
