Why can't templates be declared in a function?

后端 未结 7 700
甜味超标
甜味超标 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条回答
  • 2020-12-01 12:37

    The short answer to why this is, is because that how the guys who wrote the c/c++ compilers and standards wanted it to be. Templates inside functions must have been deemed too chaotic and/or difficult to understand or parse, so they forbade it.

    0 讨论(0)
  • 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()<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.

    0 讨论(0)
  • 2020-12-01 12:39

    What exactly would be the use? So you can declare template variables that you can only use within the function? Is that really useful?

    0 讨论(0)
  • 2020-12-01 12:42

    My guess is that it is hard to implement, that's why it is not allowed (in Standard C++03). Writing class templates outside of functions is an acceptable solution from the other hand.

    0 讨论(0)
  • 2020-12-01 12:58

    It means you cannot do something like the following

      void foo()
      {
           template <typename T> //Error
           T something;
      }
    

    Template declarations are only permitted at global, namespace, or class scope. :)

    What is the reasoning behind it?

    It is not allowed because the Standard says so .

    ISO C++-98 (Section 14.2)

    A template declaration can appear only as a namespace or class scope declaration.

    Does that make sense?

    0 讨论(0)
  • 2020-12-01 12:59

    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.

    0 讨论(0)
提交回复
热议问题