Why can't templates be declared in a function?

后端 未结 7 711
甜味超标
甜味超标 2020-12-01 12:28

Reading C++ Templates: The Complete Guide and it says

Note that templates cannot be declared in a function

It does not give e

7条回答
  •  猫巷女王i
    2020-12-01 12:38

    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()(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 = []() { return sizeof(T); };
        static_assert(4 == size.operator()());
    

    GCC already supports this syntax.

提交回复
热议问题