请问如何在一个模板中定义类型未知的函数呢?
我需要将一段程序的多个步骤和其中的某个操作分离,比如说:
#include <iostream>
template <typename T>
T adder(T a, T b)
{
return a + b;
}
template <T F(T, T)> //--- Here
T executor(T a, T b)
{
return F(a, b);
}
int main()
{
std::cout << executor<adder>(1, 2);
std::cout << executor<adder>(3.0f, 4.0f);
return 0;
}
但是上面template <T F(T, T)>中的T是不能被编译器识别的,怎样解决这个问题呢?
我自己找到答案了,这个贴就让沉掉吧(不知道怎么关闭╮(╯▽╰)╭):
#include <iostream>
template <typename T>
T adder(T a, T b)
{
return a + b;
}
template <typename T, T F(T, T)>
T executor(T a, T b)
{
return F(a, b);
}
int main()
{
std::cout << executor<int, adder>(1, 2);
std::cout << executor<float, adder>(3.0f, 4.0f);
return 0;
}
Here you must first determine the type of adder before you can infer the type of executor. The type of adder in the source program is determined by the function parameters of the executor. There is a problem in deriving the sequence, so it can be solved by manually giving the adder type. Surely maybe there is a better way?