【发布时间】:2022-01-27 03:47:01
【问题描述】:
我需要将模板函数传递给函数。
到目前为止,我还没有在 google 上找到任何好的建议。 这是我尝试过的:
#include <iostream>
#include <sstream>
using namespace std;
struct event {
bool signal;
};
template<typename T>
void out_stream(T &stream, event &evt) {
stream << evt.signal;
}
template <typename F>
void doOperation(F f)
{
event test;
test.signal = 0;
stringstream ss;
f(ss, test);
}
int main() {
doOperation(out_stream);
return 0;
}
这就是编译器给我的错误:
main.cc:27:3: error: no matching function for call to 'doOperation'
doOperation(out_stream);
^~~~~~~~~~~
main.cc:16:6: note: candidate template ignored: couldn't infer template argument 'F'
void doOperation(F f)
^
1 error generated.
一些(我希望)关于我的 g++ 编译器设置的有用信息:
- Apple clang 版本 13.0.0 (clang-1300.0.29.30)
- 目标:x86_64-apple-darwin20.6.0
- 线程模型:posix
提前谢谢你:)
【问题讨论】:
-
在您的情况下,将
T更改为ostream并删除模板。通常,将函数包装在通用 lambda 中。 -
不接受模板,您可以接受类型为
template<typename T> using F = void (*)(T&, event&);的函数指针,专门用于stringstream。
标签: c++ function templates compiler-errors