C++模板:模板参数键的语法

c++ templates : syntax of template-parameter-key

本文关键字:语法 参数 模板 C++      更新时间:2023-10-16

参考:在 c++ 工作草案 (n4527) 14.1 中

类型参数的语法:

    type-parameter-key ...(opt) identifier
    type-parameter-key identifier(opt) = type-id

这里什么是可选的 - 请有人为我提供带有选项的示例它的用例是什么?

       template<typename = int>  // this is complied in vs2015 
       void fun(int x){
        }
        int main(){
               fun(10);
        }
type-parameter-key ...(opt) identifier(opt)

这是为了支持可变参数模板,即具有任意数量的模板参数的模板:

template <typename        > //neither optionals
template <typename...     > //opt 1
template <typename    Args> //opt 2
template <typename... Args> //both

这些有无数的用途,例如工厂方法:

template <typename T, typename... Args>
T make_t (Args&&... args) {
    return {std::forward<Args>(args)...};
}

type-parameter-key identifier(opt) = type-id

这是为了支持具有默认参数的模板参数:

template <typename   = void> //without optional
template <typename T = void> //with

默认模板参数也有广泛的用途。一个很好的例子是标准库容器的分配器:

template<
    class T,
    class Allocator = std::allocator<T>
> class vector;
std::vector<int> a; //same as std::vector<int, std::allocator<int>>

另一个例子是使用SFINAE:

template <typename T, typename = void>
struct has_foo : std::false_type{};
template <typename T>
struct has_foo<T, std::void_t<T::foo>>
: std::true_type{};