Template:通过函数原型确定模板参数
Template: Determine template arguments by function prototype
我有函数指针类型或函数原型:
int function (int arg);
typedef int (*function_t) (int arg);
和类似的模板类
template <typename T_ret, typename... T_args>
class caller {
T_ret (*m_p) (T_args... args);
public:
T_ret call (T_args... args) {
return m_p(args);
}
caller (T_ret (*p)(T_args...args)) : m_p(p) {}
};
是否可以让编译器自动确定等代码中的模板参数
class caller2 : public caller <__something_with_function_prototype__> {
caller2 : caller (function) {};
};
类似的问题是:是否可以用另一个模板类而不是函数来实现这一点?
template <typename T_ret, typename... T_args> class example;
typedef example<int, int> example_t;
谢谢。
不确定这是否是您想要的,但可能是:
#include <iostream>
int function (int arg) { return arg; }
typedef int (*function_t) (int arg);
template <typename T_ret, typename... T_args>
class caller {
T_ret (*m_p) (T_args... args);
public:
T_ret call (T_args... args) {
return m_p(args...);
}
caller (T_ret (*p)(T_args...args)) : m_p(p) {}
};
template <typename T_ret, typename... T_args>
caller<T_ret, T_args...> get_caller(T_ret(*prototype)(T_args...))
{
return caller<T_ret, T_args...>(prototype);
}
int main()
{
function_t f = &function;
auto c = get_caller(f);
std::cout << c.call(1) << std::endl;
return 0;
}
实时演示链接。
或者:
#include <iostream>
int function (int arg) { return arg; }
typedef int (*function_t) (int arg);
template <typename T>
class caller {};
template <typename T_ret, typename... T_args>
class caller<T_ret(*)(T_args...)> {
T_ret (*m_p) (T_args... args);
public:
T_ret call (T_args... args) {
return m_p(args...);
}
caller (T_ret (*p)(T_args...args)) : m_p(p) {}
};
int main()
{
caller<decltype(&function)> c(&function);
std::cout << c.call(1) << std::endl;
return 0;
}
还有另一个现场演示链接。
您可以使用一些助手:
template <typename F> struct helper;
template <typename T_ret, typename... T_args>
struct helper<T_ret (*) (T_args... args)>
{
using type = caller<T_ret, T_args...>;
};
然后像一样使用
int function (int arg);
class caller2 : public helper<decltype(&function)>::type {
public:
caller2() : caller (&function) {}
};
更通用:
template <typename T_ret, typename... T_args>
struct helper<T_ret (*) (T_args... args)>
{
template <template <typename, typename...> class C>
using type = C<T_ret, T_args...>;
};
然后
class caller2 : public helper<decltype(&function)>::type<caller> {
public:
caller2() : caller (&function) {}
};
因此CCD_ 1是CCD_ 2
相关文章:
- 如何反转整数参数包
- 什么..(省略号)作为函数原型中唯一的函数参数,C++?
- 试图使用int []作为打字模板,编译器未识别函数最小的原型中的参数
- 我如何在C 中创建一个函数原型,该函数原型接受两个整数作为参数并返回其差异
- C++构造函数原型参数
- 将模板原型作为模板参数传递 - 是否可能
- 如何将用户输入作为参数传递给函数原型
- 为什么函数原型中没有参数是首选
- 当一个参数在函数原型中被赋值时,这意味着什么
- Template:通过函数原型确定模板参数
- 如何用函数原型返回多个参数
- 我不能有一个将多个整数作为参数的构造函数方法/原型吗?阿杜伊诺
- 函数原型中的参数名称
- 在头文件中使用std::vector作为输入参数定义函数原型
- 函数原型和数组参数
- 函数原型中不同的参数名称
- C++:使用一个函数的输出作为带有函数原型的头文件中另一个函数的参数
- 为什么这个参数在regex_match的原型中排序
- 函数原型和参数强制
- 为什么函数原型中的参数数量与定义中的参数不匹配