引用: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{};
关于时间:2019-03-14 标签:c++templates: syntax of template-parameter-key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35287341/