c++templates

Function Templates as alias


I have a function template with variadic arguments and I wanted to use its instantiation as a template parameter.

template <typename... Args>
constexpr auto foo (Args&&... args) noexcept {
  ...
}

Somewhere:

class X {
public:
  using myFoo = int (foo)<int,int,int>(int,int,int)

  X() {
   // I would like to have something like that
   call<myFoo>();
  }

  template <typename op>
  auto call () {
    return op(1,2,3);
  }
};

The compiler does not accept this code above. Is it possible to declare an alias for a function and to use it as a template parameter?


Solution

  • You are confusing types with values in more than one occasion. I assume you want to instantiate call with a callable (a value), not just a type. A function type consists, loosely speaking, of its signature. That's not going to help when you want to call the function.

    template <typename... Args>
    constexpr auto foo (Args&&... args) noexcept {
        return 42;
    }
    
    class X {
    public:
    
      // type alias wouldn't be sufficient here. 
      // Generally you cant call a function by only knowing its type.
      static constexpr auto& myFoo = foo<int,int,int>;
    
    
      template <auto op>   // non-type template argument
      auto call () {
        return op(1,2,3);
      }
    
      X() {
       call<myFoo>();
      }
    };
    

    Live Demo

    PS: That foo<int,int,int> is instantiation of a function template does not matter that much. Once instantiated, it's a function. You'd face the same problem and the above works the same if you replace foo<int,int,int> with some ordinary function bar.