用于查找参数是否为类的不同模板语法 [英] Different template syntax for finding if argument is a class or not
问题描述
阅读此问题,我遇到了 @Johannes 的回答。 / p>
模板< typename> struct void_ {typedef void type; };
template< typename T,typename = void> // Line 1
struct is_class {static bool const value = false; };
template< typename T>
struct is_class< T,typename void_< int T :: *> :: type> {// Line 2
static bool const value = true;
};
此结构用于查找给定类型是一个类或不是。什么困惑我是写这个小元程序的新的语法。任何人都可以详细解释:
- 为什么我们需要第1行?
- 语法
< int
作为
T :: *>模板
?第1行:如果测试成功,选择下面的部分专业化。第1行:如果测试成功,选择下面的部分专业化。 > - Why we need Line 1 ?
- What is the meaning of syntax
<int T::*>
astemplate
parameter in Line 2 ?
第2行: int T :: *
仅在 T
是一个类类型,因为它表示一个成员指针。
这样,如果它是有效的, void_< T& / code>产生
void
,使用值 $ c> true
。
如果 T
不是类类型,那么由于SFINAE,这个部分专门化不在图片中,它默认返回一个具有 value
of false
。
每次您看到 T :: SOMETHING
,如果 SOMETHING
不存在,无论是类型,数据成员还是简单的指针定义, SFINAE进行。
While reading this question , I came across @Johannes's answer.
template<typename> struct void_ { typedef void type; };
template<typename T, typename = void> // Line 1
struct is_class { static bool const value = false; };
template<typename T>
struct is_class<T, typename void_<int T::*>::type> { // Line 2
static bool const value = true;
};
This construct finds if the given type is a class or not. What puzzles me is the new kind of syntax for writing this small meta program. Can anyone explain in detail:
Line 1: Choosing the partial specialization below if the test succeeds.
Line 2: int T::*
is only valid if T
is a class type, as it denotes a member pointer.
As such, if it is valid, void_<T>::type
yields void
, having this partial specialization chosen for the instantiation with a value
of true
.
If T
is not of class type, then this partial specialization is out of the picture thanks to SFINAE and it defaults back to the general template with a value
of false
.
Everytime you see a T::SOMETHING
, if SOMETHING
isn't present, be it a type, a data member or a simple pointer definition, you got SFINAE going.
这篇关于用于查找参数是否为类的不同模板语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!