Reputation: 8001
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)
Upvotes: 14
Views: 3173
Reputation: 217075
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>;
};
In C++20, you might use constraint:
template <typename T>
requires (std::is_pointer_v<T>)
struct MyTemplate
{
};
Upvotes: 21