簡體   English   中英

C++ 元程序,成員類型測試?

[英]c++ metaprogram, member type test?

我嘗試編寫一個模板元函數來測試“類型T是否具有成員類型,名為type ”。

這是代碼:


#include <iostream>
#include <type_traits>

template <typename T, typename E = void>
struct has_type;
// branch 1
template <typename T, typename E>
struct has_type : std::false_type {};
// branch 2
template <typename T>
struct has_type<
    T, std::enable_if_t<std::is_same_v<typename T::type, typename T::type>, T>
> : std::true_type {};


struct with_type {using type = void;};
struct without_type {};

int main()
{
    std::cout<< has_type< with_type >::value <<std::endl;
    std::cout<< has_type< without_type >::value <<std::endl;
    return 0;
}

我想,編譯器會首先嘗試使用分支 2,如果類型T有成員類型type ,我們得到std::true_type 或者找不到T::type ,然后 SFINAE 並使用分支 1,我們得到std::false_type

但是這兩個輸出都是false

有什么我理解錯誤的嗎?

分支 1,即主模板,第二個模板參數的默認值為void 為了使分支 2,即要選擇的專業化,當條件滿足時,第二個模板參數應該產生類型void而不是T

// branch 2
template <typename T>
struct has_type<
    T, std::enable_if_t<std::is_same_v<typename T::type, typename T::type>, void>
//                                                                          ^^^^
> : std::true_type {};

要不就

template <typename T>
struct has_type<
    T, std::void_t<typename T::type>
> : std::true_type {};

居住

暫無
暫無

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

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