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;
}
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.
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.
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.
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 ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With