[英]Can I use enable_if together with typedef?
我想定義一個類型取決於某些條件的變量。 我想要這樣的東西:
typedef typename enable_if<cond, int>::type Type;
typedef typename enable_if<!cond, double>::type Type;
但是編譯器說我重新定義了類型。
我怎樣才能做到這一點?
我可以將
enable_if
與typedef一起使用嗎?
不,你不能。 如果條件為假,則std::enable_if
將類型std::enable_if
為undefined。 僅當條件為true時,才定義成員type
。
template< bool B, class T = void > struct enable_if;
如果
B
為true
,則std::enable_if
具有公共成員typedef類型,等於T
; 否則,沒有成員typedef。
為了使typedef正常工作,當條件為true和false時,這兩種情況都需要一個類型。 enable_if
的實現是為了協助與SFINAE相關的場景。
所以呢
我怎樣才能做到這一點?
使用std::conditional
。 條件的條件true
與false
都將包含一個成員typedef( type
)。
template< bool B, class T, class F > struct conditional;
提供構件的typedef類型,其被定義為
T
如果B
是true
在編譯時,或作為F
如果B
是false
。
因此,以下內容就足夠了;
typedef typename std::conditional<cond, int, double>::type Type;
或更簡潔;
using Type = std::conditional_t<cond, int, double>;
您需要使用std::conditional
:
#include <type_traits>
// c++11:
typedef typename std::conditional<cond, int, double>::type Type;
// c++14:
typedef std::conditional_t<cond, int, double> Type;
另請注意,自c ++ 11起,您可以將using
關鍵字用於類型和模板別名(我認為這樣更簡潔):
// c++11
using Type = typename std::conditional<cond, int, double>::type;
// c++14
using Type = std::conditional_t<cond, int, double>;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.