The variadic template of C++ is powerful, but it's hard to write such code. Here comes my question: how to pass the construction of Class
(see following code snippet) through template?
Note: because I want get a general solution, so the arguments of construction must be variadic. Besides, I want set default values of each argument.
Anybody could help me?
#include <iostream>
#include <utility>
template< typename R, typename C, typename... Args>
class delegate
{
public:
template<R(C::*F)(Args...)>
struct adapter
{
static R invoke_no_fwd(Args... args)
{
C t; // how to pass the construction function of C through template??? and set default value for each argument
return (t.*F)(args...);
}
};
};
class Class
{
public:
Class(int param)
: m_val(param)
{}
void print(int v)
{
std::cout << "Class: " << v + m_val << std::endl;
}
private:
int m_val;
};
int main(int argc, char** argv)
{
using namespace std;
// because the below code doesn't contain construction info, so it won't compile
typedef void(*function_t)(int);
function_t ptrFunc = (delegate<void, Class, int>::adapter<&Class::print>::invoke_no_fwd);
auto type = (delegate<void, Class, int>::adapter<&Class::print>::invoke_no_fwd);
cout << typeid(type).name() << endl;
return 0;
}