Default template function specialization

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); } 
+5
source share
2 answers

You can do static_assert depending on the template parameter T , then it will not be evaluated until the instance is created, i.e. the time when the exact type is considered as an argument to the template. eg.

 template<class T> T get(const std::string&) { static_assert(!std::is_same<T, T>::value, "unsupported data type"); return T(0); } 

Live

+1
source

You can do

 template <typename> struct AlwaysFalse : false_type {}; template<class T> T Foo::get(const std::string&) { static_assert(AlwaysFalse<T>::value, "unsupported data type"); } 

So the statement is template dependent.

+1
source

Source: https://habr.com/ru/post/1269557/


All Articles