简体   繁体   中英

Identifying primitive types in templates

I am looking for a way to identify primitives types in a template class definition.

I mean, having this class:

template<class T>
class A{
void doWork(){
   if(T isPrimitiveType())
     doSomething();
   else
     doSomethingElse(); 
}
private:
T *t; 
};

Is there is any way to "implement" isPrimitiveType().

UPDATE : Since C++11, use the is_fundamental template from the standard library:

#include <type_traits>

template<class T>
void test() {
    if (std::is_fundamental<T>::value) {
        // ...
    } else {
        // ...
    }
}

// Generic: Not primitive
template<class T>
bool isPrimitiveType() {
    return false;
}

// Now, you have to create specializations for **all** primitive types

template<>
bool isPrimitiveType<int>() {
    return true;
}

// TODO: bool, double, char, ....

// Usage:
template<class T>
void test() {
    if (isPrimitiveType<T>()) {
        std::cout << "Primitive" << std::endl;
    } else {
        std::cout << "Not primitive" << std::endl;
    }
 }

In order to save the function call overhead, use structs:

template<class T>
struct IsPrimitiveType {
    enum { VALUE = 0 };
};

template<>
struct IsPrimitiveType<int> {
    enum { VALUE = 1 };
};

// ...

template<class T>
void test() {
    if (IsPrimitiveType<T>::VALUE) {
        // ...
    } else {
        // ...
    }
}

As others have pointed out, you can save your time implementing that by yourself and use is_fundamental from the Boost Type Traits Library, which seems to do exactly the same.

Boost TypeTraits has plenty of stuff.

I guess this can do the job quite nicely, without multiple specializations:

# include <iostream>
# include <type_traits>

template <class T>
inline bool isPrimitiveType(const T& data) {
    return std::is_fundamental<T>::value;
}

struct Foo {
    int x;
    char y;
    unsigned long long z;
};


int main() {

    Foo data;

    std::cout << "isPrimitiveType(Foo): " << std::boolalpha
        << isPrimitiveType(data) << std::endl;
    std::cout << "isPrimitiveType(int): " << std::boolalpha
        << isPrimitiveType(data.x) << std::endl;
    std::cout << "isPrimitiveType(char): " << std::boolalpha
        << isPrimitiveType(data.y) << std::endl;
    std::cout << "isPrimitiveType(unsigned long long): " << std::boolalpha
        << isPrimitiveType(data.z) << std::endl;

}

And the output is:

isPrimitiveType(Foo): false  
isPrimitiveType(int): true  
isPrimitiveType(char): true  
isPrimitiveType(unsigned long long): true

The following example (first posted in comp.lang.c++.moderated) illustrates using partial specialisation to print things differently depending on whether or not they are built-in types.

// some template stuff
//--------------------
#include <iostream>
#include <vector>
#include <list>

using namespace std;

// test for numeric types
//-------------------------
template <typename T> struct IsNum {
    enum { Yes = 0, No = 1 };
};


template <> struct IsNum <int> { 
    enum { Yes = 1, No = 0 };
};


template <> struct IsNum <double> {
    enum { Yes = 1, No = 0 };
};

// add more IsNum types as required

// template with specialisation for collections and numeric types
//---------------------------------------------------------------
template <typename T, bool num = false> struct Printer {
    void Print( const T & t ) {
        typename T::const_iterator it = t.begin();
        while( it != t.end() ) {
            cout << *it << " ";
            ++it;
        }
        cout << endl;
    }
};

template <typename T> struct Printer <T, true> {
    void Print( const T & t ) {
        cout << t << endl;
    }
};

// print function instantiates printer depoending on whether or
// not we are trying to print numeric type
//-------------------------------------------------------------
template <class T> void MyPrint( const T & t ) {
    Printer <T, IsNum<T>::Yes> p;
    p.Print( t );
}

// some test types
//----------------
typedef std::vector <int> Vec;
typedef std::list <int> List;

// test it all
//------------
int main() {

    Vec x;
    x.push_back( 1 );
    x.push_back( 2 );
    MyPrint( x );        // prints 1 2

    List y;
    y.push_back( 3 );
    y.push_back( 4 );
    MyPrint( y );        // prints 3 4

    int z = 42;
    MyPrint( z );        // prints 42

    return 0;
}

There is a better way - using SFINAE. With SFINAE you don't have to list out every primitive type. SFINAE is a technique that depends on the idea that when template specialization fails it falls back to a more general template. ( it stands for "Specialization failure is not an error" ).

Also you don't really define if you consider a pointer to be a primitive type, so I'll make you templates for all the combinations.

// takes a pointer type and returns the base type for the pointer.
// Non-pointer types evaluate to void.
template < typename T > struct DePtr                       { typedef void R; }; 
template < typename T > struct DePtr< T * >                { typedef T R; };
template < typename T > struct DePtr< T * const >          { typedef T R; };
template < typename T > struct DePtr< T * volatile >       { typedef T R; };
template < typename T > struct DePtr< T * const volatile > { typedef T R; };

// ::value == true if T is a pointer type
template < class T > struct IsPointer                        { enum { value = false }; };
template < class T > struct IsPointer < T *                > { enum { value = true };  };
template < class T > struct IsPointer < T * const          > { enum { value = true };  };
template < class T > struct IsPointer < T * volatile       > { enum { value = true };  };
template < class T > struct IsPointer < T * const volatile > { enum { value = true };  };

// ::value == true if T is a class type. ( class pointer == false )
template < class T > struct IsClass 
{
   typedef u8 yes; typedef u16 no; 
   template < class C >    static yes isClass( int C::* );
   template < typename C > static no  isClass( ... );
   enum { value = sizeof( isClass<T>( 0 )) == sizeof( yes ) };
};

// ::value == true if T* is a class type. ( class == false )
template < class T > struct IsClassPtr 
{
   typedef u8 yes; typedef u16 no; 
   template < class C >    static yes isClass( int C::* );
   template < typename C > static no  isClass( ... );
   enum { value = sizeof( isClass< typename DePtr< T >::R >( 0 )) == sizeof( yes ) };
};

// ::value == true if T is a class or any pointer type - including class and non-class pointers.
template < class T > struct IsClassOrPtr : public IsClass<T> { };
template < class T > struct IsClassOrPtr < T *                > { enum { value = true };  };
template < class T > struct IsClassOrPtr < T * const          > { enum { value = true };  };
template < class T > struct IsClassOrPtr < T * volatile       > { enum { value = true };  };
template < class T > struct IsClassOrPtr < T * const volatile > { enum { value = true };  };


template < class T > struct IsClassOrClassPtr : public IsClass<T> { };
template < class T > struct IsClassOrClassPtr < T *                > : public IsClassPtr< T*                > { };
template < class T > struct IsClassOrClassPtr < T * const          > : public IsClassPtr< T* const          > { };
template < class T > struct IsClassOrClassPtr < T * volatile       > : public IsClassPtr< T* volatile       > { };
template < class T > struct IsClassOrClassPtr < T * const volatile > : public IsClassPtr< T* const volatile > { };

It cannot be done exactly the way you asked. Here is how it can be done:

template<class T>
class A{
void doWork(){
   bool isPrimitive = boost::is_fundamental<T>::value;
   if(isPrimitive)
     doSomething();
   else
     doSomethingElse(); 
}
private:
T *t; 
};

You may get a warning if you put the value of isPrimitive directly inside the if statement. This is why i introduced a temporary variable.

Yet another similar examples:

#include  <boost/type_traits/is_fundamental.hpp>
#include <iostream>

template<typename T, bool=true>
struct foo_impl
{
    void do_work()
    {
        std::cout << "0" << std::endl;
    }
};
template<typename T>
struct foo_impl<T,false>
{
    void do_work()
    {
        std::cout << "1" << std::endl;
    }
};

template<class T>
struct foo
{
    void do_work()
    {
        foo_impl<T, boost::is_fundamental<T>::value>().do_work();
    }
};


int main()
{
    foo<int> a; a.do_work();
    foo<std::string> b; b.do_work();
}

Assuming by 'Primitive Type' you mean the built in types you can do a series of template specializations. Your code would become:

template<class T>
struct A{
    void doWork();
private:
    T *t; 
};

template<> void A<float>::doWork()
{
    doSomething();
}

template<> void A<int>::doWork()
{
    doSomething();
}

// etc. for whatever types you like

template<class T> void A<T>::doWork()
{
    doSomethingElse();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM