簡體   English   中英

檢查模板參數是否為引用[C ++ 03]

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

我想在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
}

有什么特別的問題嗎? 誰能為我提供更好的解決方案?

你可以更容易地做到這一點:

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

幾年前,我寫了這個:

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

對我而言,它似乎比你的解決方案簡單。

然而,它只使用了幾次,可能會遺漏一些東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM