[英]how to pass construction function(variadic arguments) as template parameter?
The variadic template of C++ is powerful, but it's hard to write such code. C ++的可变参数模板功能强大,但是很难编写这样的代码。 Here comes my question: how to pass the construction of Class
(see following code snippet) through template? 我的问题来了:如何通过模板传递Class
的构造(请参见以下代码段)?
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;
}
You may do the following with std::integral_constant<typename T, T>
: 您可以使用std::integral_constant<typename T, T>
:
template< typename R, typename C, typename... Args>
class delegate
{
public:
template<R(C::*F)(Args...), typename ... Ts>
struct adapter {
static R invoke_no_fwd(Args... args) {
C t((Ts::value)...);
return (t.*F)(args...);
}
};
};
And use it like: 并像这样使用它:
int main()
{
//using namespace std;
typedef void(*function_t)(int);
function_t ptrFunc = (delegate<void, Class, int>::adapter<&Class::print, std::integral_constant<int, 42> >::invoke_no_fwd);
auto type = (delegate<void, Class, int>::adapter<&Class::print, std::integral_constant<int, 42>>::invoke_no_fwd);
ptrFunc(-42);
type(0);
return 0;
}
Live example . 现场例子 。
alloctor uses macro to call destructor. 分配器使用宏来调用析构函数。
template<class _Ty> inline
void _Destroy(_Ty _FARQ *_Ptr)
{ // destroy object at _Ptr
_DESTRUCTOR(_Ty, _Ptr);
}
#define _DESTRUCTOR(ty, ptr) (ptr)->~ty()
can this solve you problem? 这样可以解决您的问题吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.