6

我想在 C++03 中检查模板参数是否属于引用类型。(我们is_reference在 C++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
}

有什么特别的问题吗?谁能给我一个更好的解决方案?

4

2 回答 2

15

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

template <typename T> struct IsRef {
  static bool const result = false;
};
template <typename T> struct IsRef<T&> {
  static bool const result = true;
};
于 2011-12-13T09:11:55.417 回答
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> {};

对我来说,这似乎比您的解决方案更简单。

但是,它只使用过几次,可能会遗漏一些东西。

于 2011-12-13T09:10:14.257 回答