How to know if the argument that is passed to the function is a class, union or enum in c++?

前端 未结 4 443
伪装坚强ぢ
伪装坚强ぢ 2021-01-03 07:14

I want to define an operator<< for all enums, to cout the value and print that it is an enum like this:

code:

enum AnyEnum{A,B,C};
AnyEnum enm          


        
4条回答
  •  悲&欢浪女
    2021-01-03 08:01

    I am interested how to identify if the veriable is a class type, union type or an enum (in compile time).

    boost::type_traits

    Even C++ TR1 has got a header to support that functionality. In C++0x everything's gonna be a lot better.

    For example the following machinery makes use of SFINAE to check whether the argument passed is a class type:

    templatestruct Check_If_T_Is_Class_Type
    {
        template static char func (char C::*p);
        template static long func (...);
        enum{val = CHECKER(func,Check_If_T_Is_Class_Type)};
    };
    

    The MACRO CHECKER is

    #define CHECKER(func_name,class_name) \
    sizeof(class_name::template func_name(0)) == 1
    

    To understand how type_traits work you need to have some basic knowledge of templates including template metaprogramming and SFINAE.

提交回复
热议问题