Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking whether a template argument is a reference [C++03]

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?

like image 964
Prasoon Saurav Avatar asked Dec 13 '11 09:12

Prasoon Saurav


People also ask

Can we pass Nontype parameters to templates?

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.

What is a template argument C++?

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.

What is the difference between typename and class in template?

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.


2 Answers

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;
};
like image 72
bitmask Avatar answered Oct 22 '22 15:10

bitmask


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.

like image 7
sbi Avatar answered Oct 22 '22 15:10

sbi