I have a c++ template class, which only operates correctly if the templatized type is plain old data. Anything with a constructor that does anything will not work correctly.
I'd like to somehow get a compiletime or runtime warning when someone tries to do so anyway.
//this should generate error
myclass<std::string> a;
//this should be fine
myclass<int> b;
is there a trick to do this?
#include <type_traits>
template<typename T>
class myclass
{
static_assert(std::is_pod<T>::value, "T must be POD");
// stuff here...
};
The above will cause a compilation error if you pass a non-POD type as the template parameter. This solution requires C++11 for the <type_traits>
header and static_assert
keyword.
EDIT: You can also implement this in C++03 if your compiler supports TR1 (most do):
#include <tr1/type_traits>
template<typename T>
class myclass
{
static char T_must_be_pod[std::tr1::is_pod<T>::value ? 1 : -1];
// stuff here...
};