模板参数推导问题
#include <cstdio>
#include <boost/lexical_cast.hpp>
template <typename T, T f> struct WapperFunction;
template <typename RetType, RetType (*f)()>
struct WapperFunction<RetType(*)(), f>
{
static void call()
{
RetType x = f();
printf("Call result of 0X%p {%s} is %s {%s}\n\n", f, typeid(f).name(),
boost::lexical_cast<std::string>(x).c_str(), typeid(x).name());
}
};
template <typename RetType, typename Arg1Type, RetType (*f)(Arg1Type)>
struct WapperFunction<RetType(*)(Arg1Type), f>
{
static void call()
{
Arg1Type arg1;
RetType ret;
printf("Enter the argument1{%s}:", typeid(Arg1Type).name());
std::cin>>arg1;
ret = f(arg1);
printf("Call result of 0X%p {%s} is %s {%s}\n\n", f, typeid(f).name(),
boost::lexical_cast<std::string>(ret).c_str(), typeid(ret).name());
}
};
int f1()
{
return 0;
}
int f2(int x)
{
return x * x;
}
int main()
{
WapperFunction<int(*)(), f1>::call();
WapperFunction<int(*)(int), f2>::call();
};
运行效果如:
Call result of 0X00441361 {int (__cdecl*)(void)} is 0 {int}
Enter the argument1{int}:23
Call result of 0X00441906 {int (__cdecl*)(int)} is 529 {int}
现在的问题是 WapperFunction<int(*)(int), f2>::call(); 的调用中第一个模板参数 int(*)(int) 是可以从第二个参数 f2 中推导出来的。但应该如何使用才能让它进行推导? 使调用方式为:
WapperFunction<f1>::call();
WapperFunction<f2>::call();
或者有办法在运行期来生成全局函数的话,这种调用方式也可以:
WapperFunction::call(f1);
WapperFunction::call(f2);
注意生成的必须要是全局函数,不能是函数对象(需要和 C API 交互)。