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

1

8

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;
}
Planogamete answered 22/12, 2015 at 15:50 Comment(6)
You can declare type aliases inside of functions. What you have there is a template alias.Transonic
@user2079303 right. adjusted question.Planogamete
Given the current answer, "The Standard says so", could you clarify if the question was "why was it decided to not allow this?", which is how I originally read it.Bidwell
See EWG issue 95 and CWG issue 822. "EWG failed to find sufficient motivation for this extension".Selfabsorption
So, because they "failed to find sufficient motivation" to allow it.Bidwell
@BoBTFish. Thank you. Obviously the standard says so. I wanted to know why the limitation existed in the language.Planogamete
H
5

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 ]

Hallucinosis answered 22/12, 2015 at 15:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.