如何传递构造函数(可变参数)作为模板参数
how to pass construction function(variadic arguments) as template parameter?
C++的可变模板功能强大,但很难编写这样的代码。我的问题来了:如何通过模板传递Class
的构造(见下面的代码片段)?
注意:因为我想得到一个通用的解决方案,所以构造的参数必须是可变的。此外,我想设置每个参数的默认值
有人能帮我吗?
#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;
}
您可以使用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...);
}
};
};
并像一样使用它
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;
}
活生生的例子。
分配程序使用宏来调用析构函数。
template<class _Ty> inline
void _Destroy(_Ty _FARQ *_Ptr)
{ // destroy object at _Ptr
_DESTRUCTOR(_Ty, _Ptr);
}
#define _DESTRUCTOR(ty, ptr) (ptr)->~ty()
这能解决你的问题吗?
相关文章:
- 在不传递参数数量且只有3个点的情况下,如何使用变差函数
- 如何使用可变参数模板强制转换每个变体类型
- 关于如何在具有单个参数的变体构造中选择替代方案?
- 调用参数排列不变函数 f(i++, i++)
- 参数归纳与标准::变体
- 模板化回调参数的逆变,如 C# 中的逆变
- 如何在没有参数包的情况下编写变差函数
- 通过具有嵌套类的工厂类获取多个变异类模板参数包
- 获取模板参数的成员变量值列表
- 保留短 lambda 用作函数的中间参数,使用 clang 格式保持不变
- 如何定义变体<x,y,z>提取模板参数的子类型
- 正确对齐内存模板,参数顺序不变
- 递归中不同参数类型的变元模板函数
- 通过函数指针传递给变差函数的参数会更改其值
- 提升预定义为带有参数的全局 lambda 的变体访问者
- 使用可变参数模板参数提升变体访问者
- boost ::变体 - 为什么模板参数比const字符串参数具有更高的优先级
- 将变参数包中的值加载到临时数组中
- 使用额外参数提升变体访客
- 正在将动态数组元素解析为参数?(变音符)