C++模板:模板参数键的语法
c++ templates : syntax of template-parameter-key
参考:在 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{};
相关文章:
- 在标准中,模板参数的语法在哪里定义,例如,'std::function<int(char)>'?
- 将类作为主要参数的语法在哪里需要?
- 初始化对象以在 C++08 中作为参数传递的首选语法是什么?
- 当C++类函数参数之一是结构时,它们的语法有什么不同
- 将显式指定的函数模板重载作为模板参数传递的正确语法是什么?
- 提升::精神::qi::语法和可变参数模板
- C++ 中的默认参数语法和一般语法
- 带有约束的可变参数模板的'requires'表达式的语法是什么?
- C++ C 样式数组作为语法错误的参数
- 使用 MATLAB 语法的 c++ 函数参数?
- 在模板类中的参数包的语法
- 将QMETAMETHOD作为参数传递到使用新的Qobject :: Connect语法的函数
- 在Qt信号和插槽中使用lambda语法并访问传递的参数
- 是否可以在尾随返回类型语法中直接使用参数值(不是其类型,而是值本身)
- 精神语法不会编译:函数模板参数错误?
- 适用于全局模板运算符指定模板参数的适当语法
- hpp文件中的块,这是c ++语法吗?为什么没有传入参数?有人可以解释一下,请
- 有人能解释一下特殊的std::函数模板参数列表语法(这个奇怪的类型(Types..))吗
- 使用仅语法参数切换警告
- 版本80语法-参数列表中的初始化