I am trying to create a class that will work with certain data types, and I want to have a compile-time error when the data type is not supported.
I tried to specialize patterns like this.
template<> float Foo::get<float>(const std::string& key) { return std::stof(key); }
And put std::static_assert in a generic function because I only need the specified types.
template<class T> T Foo::get(const std::string&) { static_assert(false, "unsupported data type"); return T(0); }
Unfortunately, I get a compilation error (static assert failed), even if I have a specialized function for this type.
I found a way to do this only for certain types, but it looks a little silly and not generic.
T Foo::get(const std::string&) { static_assert( std::is_same<T,float>::value || std::is_same<T,double>::value || std::is_same<T,bool>::value || std::is_same<T,uint32_t>::value || std::is_same<T,int32_t>::value || std::is_same<T,std::string>::value, "unsuported data type"); return T(0); }
source share