Checking if the template argument is a link [C ++ 03]

I want to check if the template argument is a reference type or not in C ++ 03. (We already have is_reference in C ++ 11 and Boost).

I used SFINAE and the fact that we cannot have a pointer to a link.

Here is my solution

 #include <iostream> template<typename T> class IsReference { private: typedef char One; typedef struct { char a[2]; } Two; template<typename C> static One test(C*); template<typename C> static Two test(...); public: enum { val = sizeof(IsReference<T>::template test<T>(0)) == 1 }; enum { result = !val }; }; int main() { std::cout<< IsReference<int&>::result; // outputs 1 std::cout<< IsReference<int>::result; // outputs 0 } 

Any special problems? Can someone provide me a better solution?

+6
source share
2 answers

You can make it a lot easier:

 template <typename T> struct IsRef { static bool const result = false; }; template <typename T> struct IsRef<T&> { static bool const result = true; }; 
+15
source

A few years ago I wrote the following:

 //! compile-time boolean type template< bool b > struct bool_ { enum { result = b!=0 }; typedef bool_ result_t; }; template< typename T > struct is_reference : bool_<false> {}; template< typename T > struct is_reference<T&> : bool_<true> {}; 

It seems to me that this is easier than your decision.

However, this has only been used several times, and something may be missing.

+7
source

Source: https://habr.com/ru/post/903661/


All Articles