Write C ++ specific code to define a character in the std namespace

In my recent QA, I was asked to implement my own is_same

for C ++ 03 since the standard version is part of C ++ 11. The implementation was

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;
};

      

I only want it to be used if it is not defined in the namespacestd

. For example, can this be wrapped in a preprocessor block like this?

#if !defined(std::is_same)
// define is_same here
#endif

      

I want to avoid these mistakes

error: 'is_same' is not a member of 'std' // C ++ 03

error: reference to 'is_same' is ambiguous // C ++ 11

+3


source to share


1 answer


No, you can't tell if your implementation supports it std::is_same

, because that would mean inclusion <type_traits>

, which C ++ 03 doesn't have. Even if you could get around this obstacle, the metaprogramming corruptions required to detect it wouldn't be worth it.

The best you can do is to heuristically check the combination of predefined macros:



#if __cplusplus >= 201103L || _MSC_VER >= 1400 || defined(__GXX_EXPERIMENTAL_CXX0X__)
    #include <type_traits>
    #define HAS_STD_IS_SAME
#endif

namespace your_project
{
    #ifdef HAS_STD_IS_SAME
        using std::is_same;
    #else
        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; };
    #endif
}

      

But there is no benefit to that, because all implementations will implement the is_same

same as the one you provided.

+6


source







All Articles