Identifying primitive types in templates

后端 未结 8 846
南旧
南旧 2020-11-27 17:40

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

I mean, having this class :

template
class A{
void         


        
8条回答
  •  孤城傲影
    2020-11-27 18:35

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

    # include 
    # include 
    
    template 
    inline bool isPrimitiveType(const T& data) {
        return std::is_fundamental::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
    

提交回复
热议问题