Search code examples
c++templatesc++11type-deduction

Is it possible to not specify all template parameters if one of them is deduced?


Suppose I have a function like this:

template <typename T>
void f(T& x);

I can use it without specifying the type because of the type deduction:

f(5.0f); // same as f<float>(5.0f);

Suppose I change the function:

template <typename T, int N>
void f(T& x);

I now have to call it like this even if the type can be deduced

f<float, 5>(5.0f);

But I'd like to have something like this:

f<auto, 5>(5.0f); // or something like f<5>

So far I've found a way to do this:

template <int N>
struct F {
    template <typename T>
    static void f(T& x) {
         ...
    }
}

So I can now use:

F<5>::f(5.0f);

Is there any other way to do it?


Solution

  • Why not change the order of template arguments:

    template <int N, typename T>
    void f(T& x) {
      // ...
    }
    

    And call it like:

    double a;
    ...
    f<1>(a);
    

    Edit:

    You could also provide two template overloads of your function with the template arguments in reversed order and with one default argument like below:

    template <typename T, int N = 5>
    void f(T& x) {
      // ...
    }
    
    template <int N, typename T = double>
    void f(T& x) {
      // ...
    }
    

    And call it interchangeably:

    double a = 4.0;
    f(a);
    f<2>(a);
    f<double, 1>(a);
    f<double>(a); 
    

    Live Demo