[英]Template syntax explanation
On some resource I saw a code: 在一些资源上,我看到了一个代码:
struct C
{
template <typename T, typename = typename enable_if<!is_same<C, typename decay<T>::type>{}>::type>
C(T&& f){}
}
I tried my best but still need some clarification. 我已尽力而为,但仍需要澄清。 I know this scary thing is needed for the
SFINAE
idiom - if something fails the templated function simply will not be created. 我知道
SFINAE
习语需要这件可怕的事情-如果某些失败,则将不会创建模板化函数。 Here what I found: 这是我发现的:
typename decay<T>::type
- this removes cv qualifiers from type T
, or converts an array T
to pointer T
or converts T
to function pointer. typename decay<T>::type
type-从类型T
删除cv限定词,或将数组T
转换为指针T
或将T
转换为函数指针。 But what is this typename
before? typename
以前是什么? I suppose this is related to dependent type, ie the supplied type T
is a thing that is a part of another template, right? T
是另一个模板的一部分,对吗? is_same<A, B>{}
- what is this {}
braces doing here? is_same<A, B>{}
-这个{}
括号在这里做什么? Why? typename enable_if<A>::type
- as I understood if A
is true the type
field exist and in this case it's void
since only one argument was passed to enable_if
, right? typename enable_if<A>::type
据我了解,如果A
为true,则type
字段存在,并且在这种情况下它是void
因为仅将一个参数传递给enable_if
,对吗? But again - what is this typename
before? typename
以前是什么? template <typename T, typename = typename A>
- what is this typename = typename A
? template <typename T, typename = typename A>
-这是什么typename = typename A
? Where's the argument name at all?! std::decay<T>
, for example) std::decay<T>
静态变量) std::is_same
has cast operator to bool, and through {} object of that type is created and then converted to bool (at compile time). std::is_same
已将运算符std::is_same
为bool,并通过{}创建了该类型的对象,然后将其转换为bool(在编译时)。 Alternative variant is std::is_same<...>::value
std::is_same<...>::value
std::is_same
returns true, then member type of std::enable_if
is exists and SFINAE can pass through that function std::is_same
返回true,则存在std::enable_if
成员类型 ,并且SFINAE可以通过该函数 PS std::enable_if
looks like that PS
std::enable_if
看起来像这样
template<bool B, class T = void> //(1)
struct enable_if {};
template<class T> /(2)
struct enable_if<true, T> { typedef T type; };
So, if the first parameter is false then primary template (1) is selected and it has not type member, but in case when it is true specialization (2) is selected 因此,如果第一个参数为false,则选择主模板(1)并且它没有类型成员,但是如果它是true,则选择专业化(2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.