Home > Mobile >  Generalize integral template parameters
Generalize integral template parameters

Time:01-21

Is there a way to generalize an integral template parameter so that it supports e.g. int and std::size_t. Here is non-compiling example of what I have in mind. Is there a way to implement the function f without adding a copy of it that takes std::size_t as a parameter?

#include <cstddef>
#include <iostream>

template <int N>
struct foo {
    static constexpr int n = N;
    int a[N];
};

template <std::size_t N>
struct bar {
    static constexpr int n = N;
    float a[N];
};

template <template<int> typename T, int N>
void f(T<N> t) {
    std::cout << T<N>::n << " - " << N << std::endl;
}

int main() {
    bar<10> B;
    foo<20> F;

    f(B);
    f(F);
}

CodePudding user response:

In C 17, this is a simple as

template <typename T, auto N>
void f(T<N> ) { }

CodePudding user response:

Since c 17 you can use auto for non-type template parameters.

template <template<auto> typename T, auto N>
...
  •  Tags:  
  • Related