【问题标题】:Checking whether a template argument is a reference [C++03]检查模板参数是否为引用 [C++03]
【发布时间】:2011-12-13 09:05:48
【问题描述】:

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

我利用了 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
}

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

【问题讨论】:

  • 为了完整起见,您可以添加引用指针的测试用例,即IsReference&lt;int*&amp;&gt;::result

标签: c++ templates sfinae c++03


【解决方案1】:

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

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

【讨论】:

  • 有没有什么方法可以在不专门上课的情况下做同样的事情?
  • @PrasoonSaurav,这个解决方案提供了非常简单的 SFINAE 方法,专业化有什么问题,当它保证正确的结果时?事实上,您可以将此解决方案扩展到 r-value reference in c++11
【解决方案2】:

几年前,我写了这个:

//! 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> {};

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

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

【讨论】:

  • 我想避免专业化。还是一个很好的解决方案。已经投票了。
  • @GMan :由于一些未知的原因,我不能专攻这门课:P [这只是为了学习目的,与现实世界的代码无关]。
  • @PrasoonSaurav,你能不专攻任何课程或只专攻这个课程吗?如果是后者,你能有一个专门的嵌套类吗?
  • @Nim:我不能专攻任何课程(完全假设的情况)。
猜你喜欢
  • 1970-01-01
  • 2017-03-23
  • 2016-10-03
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
相关资源
最近更新 更多