compile-time function for checking type equality

后端 未结 2 1358
谎友^
谎友^ 2020-12-30 04:15

I need to implement self contained compile-time function for checking type equality (function template without arguments bool eqTypes()).

sel

相关标签:
2条回答
  • 2020-12-30 05:00

    Here's how you can do it in C, without any magic GCC extensions:

    #define CHECKED_TYPE(original_type, p) ((conversion_type*) (1 ? p : (original_type*) 0))
    

    E.g:

    void *q = CHECKED_TYPE(int, &y);
    

    Will trigger a compile error if y is not int.
    For explanation, see here.

    0 讨论(0)
  • 2020-12-30 05:03

    It's quite simple. Just define a type trait and a helper function:

    template<typename T, typename U>
    struct is_same
    {
        static const bool value = false;
    };
    
    template<typename T>
    struct is_same<T, T>
    {
        static const bool value = true;
    };
    
    template<typename T, typename U>
    bool eqTypes() { return is_same<T, U>::value; }
    

    Here is a live example.

    In C++11, if you are allowed to use std::false_type and std::true_type, you would rewrite the above this way:

    #include <type_traits>
    
    template<typename T, typename U>
    struct is_same : std::false_type { };
    
    template<typename T>
    struct is_same<T, T> : std::true_type { };
    
    template<typename T, typename U>
    constexpr bool eqTypes() { return is_same<T, U>::value; }
    

    Notice, that the type trait std::is_same, which does pretty much the same thing, is available as part of the Standard Library.

    0 讨论(0)
提交回复
热议问题