Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template template parameter of unknown type

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>
                                             ^
like image 993
Amir Kirsh Avatar asked Feb 04 '18 14:02

Amir Kirsh


People also ask

Which parameter is allowed for non-type template?

Which parameter is legal for non-type template? Explanation: The following are legal for non-type template parameters:integral or enumeration type, Pointer to object or pointer to function, Reference to object or reference to function, Pointer to member.

Can we use non-type parameters as arguments template?

Non-type template arguments are normally used to initialize a class or to specify the sizes of class members. For non-type integral arguments, the instance argument matches the corresponding template parameter as long as the instance argument has a value and sign appropriate to the parameter type.

What is template type parameter?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

What does template <> mean in C++?

Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.


1 Answers

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.

like image 177
Rakete1111 Avatar answered Oct 13 '22 06:10

Rakete1111