After seeing that a template can be partially specialized for reference or pointer types, I was wondering whether I can write a template that accepts only a pointer type to start with. This is my attempt:
template <typename T*>
struct MyTemplate{};
int main() {
MyTemplate<int *> c;
(void)c;
return 0;
}
This does not compile. How should it be modified? (i.e. if what I am trying to accomplish is at all possible)
A template has only one type, but a specialization is needed for pointer, reference, pointer to member, or function pointer types. The specialization itself is still a template on the type pointed to or referenced.
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.
A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument. A non-type parameter can be any of the following types: An integral type. An enumeration type. A pointer or reference to a class object.
A non-type template argument provided within a template argument list is an expression whose value can be determined at compile time. Such arguments must be constant expressions, addresses of functions or objects with external linkage, or addresses of static class members.
You may use partial specialization:
template <typename T> struct MyTemplate; // Declaration
template <typename T> struct MyTemplate<T*> // Specialization
{
};
or use static_assert
template <typename T> struct MyTemplate
{
static_assert(std::is_pointer<T>::value, "Expected a pointer");
// T = value_type*
using value_type = std::remove_pointer_t<T>;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With