【问题标题】:Using std::function on a templated function [duplicate]在模板函数上使用 std::function [重复]
【发布时间】: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);
}

问题似乎是函数operations1operations2 是模板化的,我不知道如何调用它们。如果我删除模板,一切正常。

我愿意接受其他建议,如果它可以使用,请将函数 callFunc 设为模板。

https://godbolt.org/z/cq5b1ozjP

谢谢

附:我知道调用callFunc(operation1&lt;std::chrono::hours&gt;, 10); 有效,但这对我没有帮助,我试图摆脱重复代码,否则我可以删除callFunc 并直接使用operation1operation2,就像我现在正在做的那样...

【问题讨论】:

标签: c++ templates


【解决方案1】:

here的问题类似,但是这个问题略有不同,因为模板不能从参数类型推导出来。

如果模板函数未在链接处实例化为答案,则无法传递或评估模板函数。

所以你应该把你的函数改成函子,

struct operation1 {
  template<typename Duration>
  void operator()(int i) {
    // do something
  }
};

并将函子传递给调用者。


template<typename Functor>
void callFunc(Functor func, int i)
{
  func.template operator()<std::chrono::hours>(i);
  func.template operator()<std::chrono::minutes>(i);
  func.template operator()<std::chrono::seconds>(i);
  func.template operator()<std::chrono::milliseconds>(i);
}

int main() {
  callFunc(operation1{}, 10);
}

【讨论】:

    【解决方案2】:

    只需将底部两行切换为:

    callFunc(opeartion1<int>, 10);  // int or any other type
    callFunc(operation2<int>, 3);
    

    说明,在完全解析所有模板类型之前,您的函数不是具体类型,从而产生编译时错误。

    【讨论】:

    • 如果我这样做,我会有很多重复的代码,这就是我想要避免的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 2020-12-17
    • 1970-01-01
    相关资源
    最近更新 更多