【问题标题】:Two time template<typename T> declaration两次 template<typename T> 声明
【发布时间】:2018-12-03 07:09:22
【问题描述】:

我从cppreference复制了这个块

template<class T>
struct Alloc { };
template<class T>
using Vec = vector<T, Alloc<T>>; // type-id is vector<T, Alloc<T>>
Vec<int> v; // Vec<int> is the same as vector<int, Alloc<int>>

我不明白为什么template&lt;typename T&gt; 声明了两次?

如果template&lt;typename T&gt; 声明属于下面的行,则必须以某种方式限定范围。

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    模板参数是占位符,它们的范围仅限于一个声明。 因此,T

    template<class T> struct Alloc { };
    

    没有连接到T中

    template<class T> using Vec = vector<T, Alloc<T>>;
    

    就像您可以在不同的函数声明中使用相同的参数名称一样。

    【讨论】:

    • 范围是模板结尾和分号之间的语句;
    • 但它属于下一行不是吗?
    • cpp中没有行,只有分号;或其他以大括号 } 结尾的语句。因此换行在那里毫无意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    • 2018-04-03
    相关资源
    最近更新 更多