我正在尝试编写一个以三件事为模板的函数:
- 第一种。
- 第二种。
- 具有参数 First 和 Second 类型的函数。
代码如下所示:
#include <iostream>
#include <typeinfo>
using namespace std;
// Assume that this function is in a library. Can't be modified.
void bar(int x, int y) {
cout << x << endl;
cout << y << endl;
}
// My code is below:
template <typename Type1, typename Type2, void (*fn)(Type1, Type2)>
void foo(Type1 x1, Type2 x2) {
fn(x1,x2);
}
int main() {
foo<int, int, &bar>(1,2);
}
该代码有效,但我对我的模板必须包含<int, int, &bar>
. 我希望编译器能弄清楚 bar 有int, int
作为参数并弄清楚。
我尝试首先列出函数,然后列出类型,但在声明Type1
中,函数原型中无法识别,因为它稍后在同一原型中定义。
有没有优雅的解决方案?
编辑:我绝对不想bar
在堆栈上传递一个指针。我想在bar
. 参数应该是 just (1, 2)
。
Edit2:我的意思是我想写foo<&bar>(1,2)
.