8

为什么我不能在函数内声明模板化类型别名?

#include <vector>

int main(){

    //type alias deceleration:
    template <typename T>
    using type = std::vector<T>;

    //type instantiation:
    type<int> t;

}

错误:模板声明不能出现在块范围内

为什么我们被迫将这些声明放在块范围之外?

#include <vector>

//type alias deceleration:
template <typename T>
using type = std::vector<T>;

int main(){

    //type instantiation:
    type<int> t;
}
4

1 回答 1

5

标准是这样说的。

来自 C++11 标准(强调我的):

14 模板

2 模板声明只能作为命名空间范围或类范围声明出现。在函数模板声明中,declarator-id 的最后一个组件不应是 template-id。[ 注意:最后一个组件可能是标识符、操作符函数 ID、转换函数 ID 或文字操作符 ID。在类模板声明中,如果类名是 simple-template-id,则声明声明类模板部分特化 (14.5.5)。——尾注]

于 2015-12-22T15:57:48.913 回答