时间:2019-03-14 标签:c++templates: syntax of template-parameter-key

标签 c++ c++11

引用: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/

相关文章:

c++ - 用C++17编译Eigen需要_SILENCE_CXX17_NEGATORS_DEPRECATION_WARNING定义

c++ - 在命名空间范围之外定义命名空间的变量成员

c++ - 如何使用这个宏来测试内存是否对齐?

c++ - 不同的 constexpr 行为 vs2015u2 vs gcc

c++ - buildroot 文件系统 & 交叉编译 : dynamically linked application fails but static ok. 如何链接 uClibc

c++ - 是否有任何功能可以知道键盘上的某个键是否被按下?

c++ - 计算结果出现奇怪的错误

c++ - 对C++递归感到困惑

c++11 - C++ STL;迭代包含STL容器的类?

c++ - 将 std::list<std::unique_ptr> 移动到 vector 中尝试引用已删除的函数