I want to check whether a template argument is of reference type or not in C++03. (We already have is_reference
in C++11 and Boost).
I made use of SFINAE and the fact that we can't have a pointer to a reference.
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 particular issues with it? Can anyone provide me a better solution?
Template classes and functions can make use of another kind of template parameter known as a non-type parameter. A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument.
A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.
There is no semantic difference between class and typename in a template-parameter. typename however is possible in another context when using templates - to hint at the compiler that you are referring to a dependent type. §14.6.
You can do this a lot easier:
template <typename T> struct IsRef {
static bool const result = false;
};
template <typename T> struct IsRef<T&> {
static bool const result = true;
};
Years ago, I wrote this:
//! 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> {};
To me it seems simpler than your solution.
However, it was only ever used a few times, and might be missing something.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With