Template Specialization for Base POD Only

Is there a subtle trick for template specialization so that I can apply one specialization to basic POD (when I say basic POD, I don't really want a struct POD (but I will take that)).

 template<typename T> struct DoStuff { void operator()() { std::cout << "Generic\n";} }; template<> struct DoStuff</*SOme Magic*/> { void operator()() { std::cout << "POD Type\n";} }; 

Or do I need to write specializations for each of the built-in types?

 template<typename T> struct DoStuff { void operator()() { std::cout << "Generic\n";} }; // Repeat the following template for each of // unsigned long long, unsigned long, unsigned int, unsigned short, unsigned char // long long, long, int, short, signed char // long double, double, float, bool // Did I forget anything? // // Is char covered by unsigned/signed char or do I need a specialization for that? template<> struct DoStuff<int> { void operator()() { std::cout << "POD Type\n";} }; 

Unit Test.

 int main() { DoStuff<int> intStuff; intStuff(); // Print POD Type DoStuff<std::string> strStuff; strStuff(); // Print Generic } 
+6
source share
3 answers

If you really want only the base types and not the user-defined POD types, then the following should work:

 #include <iostream> #include <boost/type_traits/integral_constant.hpp> #include <boost/type_traits/is_fundamental.hpp> #include <boost/type_traits/is_same.hpp> template<typename T> struct non_void_fundamental : boost::integral_constant< bool, boost::is_fundamental<T>::value && !boost::is_same<T, void>::value > { }; template<typename T, bool Enable = non_void_fundamental<T>::value> struct DoStuff { void operator ()() { std::cout << "Generic\n"; } const }; template<> struct DoStuff<T, true> { void operator ()() { std::cout << "POD Type\n"; } const }; 

If you also need custom POD types, use boost::is_pod<> instead of non_void_fundamental<> (and if you use C ++ 11 and do this for optimization, use std::is_trivially_copyable<> instead).

+6
source

In C ++ 11, many features are added to the standard library, and most of them, in particular, are aimed at interesting specializations (and, in particular, bitwise manipulations).

You may be interested in the following: std::is_trivial , but there are many others:

  • std::is_trivially_default_constructible
  • std::is_trivially_copy_constructible
  • std::is_trivially_move_constructible
  • std::is_trivially_copyable (can be copied via memcpy )

In general, the Standard tried to get the most subtle features possible, so you don’t need to rely on such broad assumptions as is_pod , but instead configure your restrictions to suit your methods.

+6
source

Boost has boost::is_pod . Is this what you are looking for?

(I never used it, so I will not embarrass myself trying to formulate the exact code that you need for your example.)

+1
source

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


All Articles