5
有許多方法可以實現has_type<T>
模板,該模板可以推導出T
是否具有名爲type
的嵌套類或typedef。即has_type模板對結構類型{}返回true;
namespace detail {
template<typename> struct tovoid { typedef void type; };
}
template<typename T, typename = void> struct has_type
: std::false_type { };
// this one will only be selected if C::type is valid
template<typename C> struct has_type<C, typename detail::tovoid<typename C::type>::type>
: std::true_type { };
或者
template <typename C> char test_for_type(...) { return '0'; }
template <typename C> double test_for_type(typename C::type const *) { return 0.0; }
template <typename T> struct has_type
{
static const bool value = sizeof(test_for_type<T>(0)) == sizeof(double);
};
然而,在這兩種情況下
,has_type<type>::value
是true
該類:
struct type
{
};
現在上面type
沒有其他type
內嵌套的,但它確實有一個構造函數type::type()
。
但應該構造函數'觸發'檢查嵌套類型?還是它是一個編譯器錯誤? (我想認爲typename type::type
並不適用於構造和/或,你不能拿一個指向一個構造函數,比如什麼會由第二測試方法來生產:typename type::type const *
?
啊,真的。我猜'結構類型{struct type {};};'是無效的,就像'struct type {typedef int type;};'。這回答我的下一個問題 - 如何處理這個案例(如果我真的想)。由ch如果T被命名爲類型,就不會太難。 – tony 2014-09-02 15:04:06
並感謝您的快速回答! – tony 2014-09-02 15:06:24
@tony難度和便攜性都比您想象的要小:http://stackoverflow.com/q/1055452/501250 – cdhowie 2014-09-02 15:08:31