简体   繁体   English

模板语法说明

[英]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: 这是我发现的:

  1. 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是另一个模板的一部分,对吗?
  2. is_same<A, B>{} - what is this {} braces doing here? is_same<A, B>{} -这个{}括号在这里做什么? Why? 为什么?
  3. 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以前是什么?
  4. 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?! 参数名称到底在哪里?
  1. Yes, typename keyword in that case says to compiler that decay::type is really type (but not static variable of std::decay<T> , for example) 是的,在这种情况下, typename关键字告诉编译器衰减:: type确实是类型(例如,不是std::decay<T>静态变量)
  2. 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
  3. If 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可以通过该函数
  4. Parameter name is not needed in that context (because it isn't used somewhere) 在此上下文中不需要参数名称(因为在某处未使用它)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM