c++;模板:模板参数键的语法 REF:C++工作草案(N45 27)14.1<P>

c++;模板:模板参数键的语法 REF:C++工作草案(N45 27)14.1<P>,c++,c++11,C++,C++11,类型参数的语法: 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

类型参数的语法:

    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);
        }
template//这在vs2015中得到了遵守
虚无乐趣(整数x){
}
int main(){
乐趣(10);;
}
这是为了支持可变模板,即具有任意数量模板参数的模板:

template <typename        > //neither optionals
template <typename...     > //opt 1
template <typename    Args> //opt 2
template <typename... Args> //both
template <typename   = void> //without optional
template <typename T = void> //with
这是为了支持带有默认参数的模板参数:

template <typename        > //neither optionals
template <typename...     > //opt 1
template <typename    Args> //opt 2
template <typename... Args> //both
template <typename   = void> //without optional
template <typename T = void> //with
template//不带可选项
模板//带有
默认模板参数也有广泛的用途。标准库容器的分配器就是一个很好的例子:

template<
    class T,
    class Allocator = std::allocator<T>
> class vector;

std::vector<int> a; //same as std::vector<int, std::allocator<int>>
模板<
T类,
类分配器=std::分配器
>类向量;
std::载体a//与std::vector相同
另一个例子是使用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{}; 
模板
结构有_foo:std::false_type{};
模板
struct有_foo
:std::true_type{};

查看wikipedia页面上的最后一个示例。从头开始:容器适配器。例如,std::stack实际上对应于std::stack,后者是默认的。此外,标准容器接受一个额外的模板参数,指定要使用的分配器。所以,std::vector实际上对应于std::vector。您可以更改这些模板参数,但大多数人不需要更改,因此它们是默认的。希望我正确理解了你的问题。
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{};