【问题标题】:Using a template function as a template param in another function在另一个函数中使用模板函数作为模板参数
【发布时间】:2021-11-26 15:12:14
【问题描述】:

我想知道,如何在 C++ 中执行以下操作?

template <typename T>
T doSomething(T x, T y) {
  T result = /*do something*/;

  return result;
}

template <typename T , typename V> 
T doMore(**input doSomething as template**, V v){
  T result = doSomething<V>(v,0); 
  return result;
}

我基本上是在尝试在另一个函数中使用带有模板值类型的模板函数,有什么办法吗?

【问题讨论】:

  • 所以您想像doMore(doSomething, some_v_value) 一样使用doMore(请edit 澄清您的问题)?然后我建议您从标准库中获取提示,其中所有函数都使用单个模板化参数类型传递。我还建议您在调用中直接使用 lambdas 而不是 doSomething
  • 您的描述确实令人困惑,尤其是因为您已经在doMore 中使用了doSomething。关于如何将任何类型的函数传递给doMore 以便它可以在内部调用它的问题是什么? (然后你可能想重命名你在该函数中调用的内容)

标签: c++ function templates c++14 std-function


【解决方案1】:

您不能将(一组)函数模板作为参数传递(但您可以传递特定的实例化)。

你可以通过函子来解决你的问题:

template <typename T>
T doSomething(T x, T y) {
  T result = /*do something*/;

  return result;
}

template <typename F, typename V> 
T doMore(F f, V v){
  T result = f(v, V{0}); 
  return result;
}

然后

doMore([](auto x, auto y){ return doSomething(x, y); }, 42);

【讨论】:

  • 我还有一个问题:当我有这样的函数调用时:doSomething(...),如何将函数定义为能够使用 double 进行调用价值观?
  • 你的doSomething 只接受一个模板参数,所以doSomething&lt;int,float&gt;(...) 是错误的。无论如何,没有办法将一个函数实例化重新映射到另一个具有不同模板的函数实例(但模板类可能是可能的)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多