Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Given the following code:

void f()
{
    class A
    {
        template <typename T>
        void g() {}
    };
}

g++ 4.4 (and also g++-4.6 -std=gnu++0x) complains: "invalid declaration of member template in local class".

Apparently local classes are not allowed to have template members. What is the purpose of this limitation? Will it be removed in C++0x?

Note: If I make the local class itself a template, rather than giving it a template member:

void f()
{
    template <typename T>
    class A
    {
        void g() {}
    };
}

I get "error: a template declaration cannot appear at block scope".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
220 views
Welcome To Ask or Share your Answers For Others

1 Answer

The purpose of this limitation? Just a guess, but:

  • you may use the template class/template member function only within the enclosing function. Therefore you already know all used types within the function and hence can directly specify the used types (for several types, of course, the template variant would have saved some typing).
  • although it might not seem so, it is work for all compiler creators and space for bugs and so it must be worth the effort.

Fun Fact: Try to use a local class within a function as a return type for a (c++0x)-lambda function declared in the function: MSVC 2010: internal compiler error ^^.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...