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;
}
Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
  • You *can* declare type aliases inside of functions. What you have there is a template alias. – eerorika Dec 22 '15 at 15:56
  • @user2079303 right. adjusted question. – Trevor Hickey Dec 22 '15 at 15:57
  • 1
    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. – BoBTFish Dec 22 '15 at 15:59
  • 2
    See [EWG issue 95](http://wg21.link/EWG95) and [CWG issue 822](http://wg21.link/CWG822). "EWG failed to find sufficient motivation for this extension". – T.C. Dec 22 '15 at 15:59
  • 1
    So, because they "failed to find sufficient motivation" to allow it. – BoBTFish Dec 22 '15 at 16:01
  • @BoBTFish. Thank you. Obviously the standard says so. I wanted to know why the limitation existed in the language. – Trevor Hickey Dec 22 '15 at 16:39

1 Answers1

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 ]

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270