Search code examples
c++functiontemplatesc++14std-function

Using a template function as a template param in another function


I was wondering, how I can do the following in 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;
}

I am basically trying to use a template function with its template valuetype in another function as such, is there any way to do that?


Solution

  • You cannot pass (the set of) function template as argument (you can pass specific instantiation though).

    You might pass functor to solve your issue:

    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;
    }
    

    And then

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