【发布时间】:2021-06-23 11:19:51
【问题描述】:
我正在尝试使用std::function 来实现这一点(代码无法编译,ofc):
template <typename Duration>
void operation1(int i)
{
// do some chrono stuff
}
template <typename Duration>
void operation2(int i)
{
// do other chrono stuff
}
void callFunc(const std::function<void(int)>& func, int i)
{
func<std::chrono::hours>(i);
func<std::chrono::minutes>(i);
func<std::chrono::seconds>(i);
func<std::chrono::milliseconds>(i);
}
int main()
{
callFunc(operation1, 10);
callFunc(operation2, 5);
}
问题似乎是函数operations1 和operations2 是模板化的,我不知道如何调用它们。如果我删除模板,一切正常。
我愿意接受其他建议,如果它可以使用,请将函数 callFunc 设为模板。
https://godbolt.org/z/cq5b1ozjP
谢谢
附:我知道调用callFunc(operation1<std::chrono::hours>, 10); 有效,但这对我没有帮助,我试图摆脱重复代码,否则我可以删除callFunc 并直接使用operation1 和operation2,就像我现在正在做的那样...
【问题讨论】:
-
使用其他人的评论,并称之为
func.template operator()<std::chrono::hours>(i);。