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

时间:2015-12-22 15:50:28

标签: c++ templates typedef c++14 template-aliases

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

#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;
}

1 个答案:

答案 0 :(得分:4)

标准是这样说的。

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

  

14模板

     

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