简体   繁体   中英

How to overload template class by type- and non-type template parameters?

Is it possible to implement a template class Type which supports the following instantiations?

Type<int> typeArg_;
Type<nullptr> nonTypeArg_;

I hope there is a solution (especially without macro). Maybe std::enable_if -magic or something will help...

No, you can't do that.

The nature of a template parameter is fixed. It is either a type or non-type (value). It can't be a type for one use case and a non-type for another use case.

There might be ways to accomplish your goal if you can elaborate what that is.

As far I now, isn't possible in C++.

The best that come in my mind is to wrap values in types; something as

template <typename T, T Value>
struct ValueWrapper
 { };

and specialize Type for ValueWrapper

Something as

template <typename T>
struct Type
 { /* something with T */ };

template <typename T, T Value>
struct Type<ValueWrapper<T, Value>>
 { /* something with value */ };

The use become

Type<int>  typeArg;
Type<ValueWrapper<std::nullptr_t, nullptr>> nonTypeArg;

or also

Type<ValueWrapper<decltype(nullptr), nullptr>> nonTypeArg;

As pointed by Jarod42 (thanks) the standard (starting from C++11) provides a standard structure that make the ValueWrapper function: std::integral_constant .

You can use it instead of ValueWrapper but doesn't works, for std::integral_constant , the following C++17 semplification.

Because if you can use C++17, all become simpler: you can use auto for value types, so ValueWrapper become

template <auto Value>
struct ValueWrapper
 { };

so Type non-type specialization become

template <auto Value>
struct Type<ValueWrapper<Value>>
 { /* something with value */ };

and the use

Type<int>  typeArg;
Type<ValueWrapper<nullptr>> nonTypeArg;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM