简体   繁体   English

将类型分配给typename关键字

[英]Assigning a type into the typename keyword

I was looking at the following template function and was wondering what happens behind the scenes when we assign the enable_if type to the typename keyword: 我正在查看以下模板函数,想知道当我们将enable_if类型分配给typename关键字时,幕后会发生什么:

template <typename T, typename = std::enable_if<std::is_pointer<T>::value>::type>
                    // ^^ What happens here?
void foo()
{
    std::cout << "T is a pointer!" << std::endl;
}

Other then the obvious SFINAE, does the compiler actually do something with it? 除了显而易见的SFINAE之外,编译器实际上是否会对它有所作为? Perhaps it generates some kind of anonymous type? 也许它会生成某种匿名类型?

Thanks 谢谢

I'll assume you're using a lenient compiler which doesn't complain about the missing typename keyword after = . 我假设您使用的是宽松的编译器,它不会抱怨=之后缺少typename关键字。

It is an unnamed template parameter which is otherwise ignored, along with a default template argument which will be used if no other template argument is specified. 它是一个未命名的模板参数,否则将被忽略,另外还有一个默认模板参数,如果未指定其他模板参数,则将使用默认模板参数。

It means that foo<void *>() resolves to foo<void *, std::enable_if<std::is_pointer<void *>::value>::type>() , which is foo<void *, void>() . 这意味着foo<void *>()解析为foo<void *, std::enable_if<std::is_pointer<void *>::value>::type>() ,它是foo<void *, void>()

It means that foo<int>() would resolve to foo<int, std::enable_if<std::is_pointer<int>::value>::type>() , except it gets rejected because std::enable_if<std::is_pointer<int>::value> doesn't have any type member. 这意味着foo<int>()将解析为foo<int, std::enable_if<std::is_pointer<int>::value>::type>() ,除了它会因为std::enable_if<std::is_pointer<int>::value>而被拒绝std::enable_if<std::is_pointer<int>::value>没有任何type成员。

It means that foo<int, int>() works and prints "T is a pointer!", since the default argument is not used if a template argument is explicitly specified. 这意味着foo<int, int>()可以工作并显示“ T是一个指针!”,因为如果显式指定了模板参数,则不使用默认参数。

That last one means this is probably not a good idea. 最后一个意味着这可能不是一个好主意。

No, we're not assigning the enable_if type to the typename keyword, the template parameter is just ommitted here, because it won't be used: 不,我们没有将enable_if类型分配给typename关键字,此处仅省略了template参数,因为它不会被使用:

template <typename T, typename Anonymous_Template_Parameter = std::enable_if<std::is_pointer<T>::value>::type>
//                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

And = makes std::enable_if<std::is_pointer<T>::value>::type> as its default argument here. And =std::enable_if<std::is_pointer<T>::value>::type>作为其默认参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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