8

Trying to extract template parameter value in the following code:

template<std::size_t SIZE>
class Foo {};

template <template<std::size_t> class T, std::size_t K>
auto extractSize(const T<K>&) {
    return K;
}

int main() {
    Foo<6> f1;
    Foo<13> f2;
    std::cout << extractSize(f1) << std::endl;
    std::cout << extractSize(f2) << std::endl;
}

(As an answer for the question: Extract C++ template parameters).

However, is there a way to do it without knowing the type of the template parameter. Something like (code below doesn't compile...):

template <template<class SIZE_TYPE> class T, SIZE_TYPE K>
auto extractSize(const T<K>&) {
    return K;
}

The compilation error on the above, is:

error: unknown type name 'SIZE_TYPE'
template <template<class SIZE_TYPE> class T, SIZE_TYPE K>
                                             ^
Amir Kirsh
  • 12,564
  • 41
  • 74
  • Did you try to put '''typename SIZE_TYPE''' at the beggining of the list? – Robert Andrzejuk Feb 04 '18 at 18:04
  • @RobertAndrzejuk Adding typename SIZE_TYPE [fails with C++14](http://coliru.stacked-crooked.com/a/8cfb21497d98525b). It does work [with C++17](http://coliru.stacked-crooked.com/a/368d3668d140ea71) - but if we are in C++17, the solution with `auto` proposed by Rakete1111 would be simpler. – Amir Kirsh Feb 08 '22 at 13:41

1 Answers1

8

auto to the rescue!

template <template<auto> class T, auto K>
auto extractSize(const T<K>&) {
    return K;
}

That way the type of the value you passed in as template parameter is automatically inferred.

Rakete1111
  • 47,013
  • 16
  • 123
  • 162