How to disable pointers as template typenames
There are a couple ways you can do this. You can use SFINAE to constrain the template to non-pointer types like
template <typename T, std::enable_if_t<!std::is_pointer_v<T>, bool> = true>
class MyClass{
//...
T payload;
//...
};
But this can give some pretty hard to understand compiler errors. Using a static_assert
you can add your own custom error message like
template <typename T>
class MyClass {
//...
static_assert(!std::is_pointer_v<T>, "MyClass<T> requires T to be a non pointer type");
T payload;
// ...
};
You can use static_assert
+ std::is_pointer_v
:
template <typename T>
class MyClass {
static_assert(!std::is_pointer_v<T>);
// ...
};
If you don't have C++11 to use std::is_pointer
and static_assert
, you can define a specialization and leave it undefined:
template <typename T>
class MyClass {
};
template<class T>
class MyClass<T*>; // Requires non-pointer types
template<class T>
class MyClass<T* const>; // Requires non-pointer types
template<class T>
class MyClass<T* const volatile>; // Requires non-pointer types
template<class T>
class MyClass<T* volatile>; // Requires non-pointer types
int main() {
MyClass<int> mc1; // Works fine
MyClass<int*> mc2; // Error
}