Why can't templates be declared in a function?

The problem is probably linked to the historical way templates were implemented: early implementation techniques (and some still used today) require all symbols in a template to have external linkage. (Instantiation is done by generating the equivalent code in a separate file.) And names defined inside a function never have linkage, and cannot be referred to outside of the scope in which they were defined.


The answer "because standard says so", is of course correct, but let's consider generic lambdas.

In C++14 and C++17 generic lambdas are the only way of writing template-like code that I know of:

    auto lambda = [](auto x) { };
    lambda.operator()<int>(0);

Technically, you can write any kind of template code just with that. Though you'll have to work hard to work around various limitations of this approach.

That will be simpler in C++20 though. With template parameter list in generic lambdas you will be able to write code like this:

    auto size = []<class T>() { return sizeof(T); };
    static_assert(4 == size.operator()<int>());

GCC already supports this syntax.