这个模板语法“typename = T"是什么?意思? [英] What this template syntax "typename = T" mean?

查看:59
本文介绍了这个模板语法“typename = T"是什么?意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我会看到这样的语法.

Sometimes I see syntax like this.

template<typename T,typename = int>
int foo(){
    //...
}

typename = int 是什么意思?可以用在哪里?

what part typename = int mean? Where it can be used?

推荐答案

foo 有两个模板参数.第一个称为 T,第二个未命名,默认为 int.

foo has two template arguments. The first is called T and the second is unnamed and defaults to int.

仅在您的一段代码中,没有理由使用第二个参数.未命名的模板参数经常出现在 SFINAE 中.cppreference 的示例:

In your piece of code alone there is no reason to use the second argument. Unnamed template arguments often come up with SFINAE. An example from cppreference:

// primary template handles non-referenceable types:
template<class T, class = void>
struct reference_traits {
    using add_lref = T;
    using add_rref = T;
};
 
// specialization recognizes referenceable types:
template<class T>
struct reference_traits<T, std::void_t<T&>> {
    using add_lref = T&;
    using add_rref = T&&;
};
 
template<class T>
using add_lvalue_reference_t = typename reference_traits<T>::add_lref;
 
template<class T>
using add_rvalue_reference_t = typename reference_traits<T>::add_rref;

主模板具有第二个参数的唯一原因是它可以被专门化.在可能的情况下,实例化更专业的专业化.如果失败(因为 T& 无效),则替换失败不是错误".(SFINAE) 启动并改为实例化主模板.

The only reason for the primary template to have a second argument is that it can be specialized. When possible the more specialized specialization is instantiatied. If this fails (because T& is not valid) then "substitution failure is not an error" (SFINAE) kicks in and the primary template is instantiated instead.

未命名参数的一个更简单的例子是,当你想要一个模板参数仅仅作为一个标签来区分不同的实例时:

A simpler example of unnamed argument is when you want a template argument merely as a tag to distinguish different instantiations:

template<typename = int>
struct bar {
    // ...
};

即使 bar 的实现不依赖于模板参数,您也可能希望 barbar 是两种不同的类型.

Even if the implementation of bar does not depend on the template argument you might want to have bar<double> and bar<std::string> be two distinct types.

这篇关于这个模板语法“typename = T"是什么?意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆