Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I declare templated type aliases inside of functions? [duplicate]

Why can't I declare a templated type alias inside of a function?

#include <vector>

int main(){

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

    //type instantiation:
    type<int> t;

}

error: a template declaration cannot appear at block scope

Why are we forced to put these declarations outside of block scope?

#include <vector>

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

int main(){

    //type instantiation:
    type<int> t;
}
like image 673
Trevor Hickey Avatar asked Dec 22 '15 15:12

Trevor Hickey


People also ask

How do you make an alias in C++?

You can use an alias declaration to declare a name to use as a synonym for a previously declared type. (This mechanism is also referred to informally as a type alias). You can also use this mechanism to create an alias template, which can be useful for custom allocators.

What is type alias in C++?

Type alias is a name that refers to a previously defined type (similar to typedef). Alias template is a name that refers to a family of types.

What are type aliases?

Type aliases create a new name for a type. Type aliases are sometimes similar to interfaces, but can name primitives, unions, tuples, and any other types that you'd otherwise have to write by hand.


1 Answers

The standard says so.

From the C++11 Standard (emphasis mine):

14 Template

2 A template-declaration can appear only as a namespace scope or class scope declaration. In a function template declaration, the last component of the declarator-id shall not be a template-id. [ Note: That last component may be an identifier, an operator-function-id, a conversion-function-id, or a literal-operator-id. In a class template declaration, if the class name is a simple-template-id, the declaration declares a class template partial specialization (14.5.5). —end note ]

like image 175
R Sahu Avatar answered Sep 21 '22 23:09

R Sahu