gpt4 book ai didi

C++ 模板 : syntax of template-parameter-key

转载 作者:搜寻专家 更新时间:2023-10-31 01:36:39 24 4
gpt4 key购买 nike

引用:在 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{};

关于C++ 模板 : syntax of template-parameter-key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35287341/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com