检查模板参数是否为引用[C++ 03]

Pra*_*rav 6 c++ templates sfinae c++03

我想在C++ 03中检查模板参数是否属于引用类型.(我们已经有了is_referenceC++ 11和Boost).

我使用了SFINAE以及我们不能指向引用的事实.

这是我的解决方案

#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
}
Run Code Online (Sandbox Code Playgroud)

有什么特别的问题吗?谁能为我提供更好的解决方案?

bit*_*ask 15

你可以更容易地做到这一点:

template <typename T> struct IsRef {
  static bool const result = false;
};
template <typename T> struct IsRef<T&> {
  static bool const result = true;
};
Run Code Online (Sandbox Code Playgroud)


sbi*_*sbi 7

几年前,我写了这个:

//! 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> {};
Run Code Online (Sandbox Code Playgroud)

对我而言,它似乎比你的解决方案简单.

然而,它只使用了几次,可能会遗漏一些东西.