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

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

c++ - class template instantiation

I just read the wiki article about CRTP, and I'm a little confused about template instantiation.

According to the wiki,

member function bodies (definitions) are not instantiated until long after their declarations.

I don't quite understand what it means.

Suppose I got a class template:

template <typename T>
class A
{
    public:
        void foo(T t)
        {
            //...
        };
};

When I instantiate the class template A, does it instantiate the member function foo()?

For example:

//in .cpp file
int main()
{
    A<int> a; //question 1
              //class template is instantiated here, isn't it? 
              //What about foo(), is it instantiated too?

    a.foo(10); //question 2
               //according to the quotation, foo() will not be instantiated until it is used.
               //if so, foo() is instantiated right here, not in question 1, right?
}
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You seem to be confusing one thing:

Instantiation happens during compilation, not during runtime. Hence you can't say "on which line" a class template or a function template was instantiated.

That said, you're right about the fact that member function templates aren't instantiated together with class templates.

You could observe it in such a case: You have the following files

  • template.h (defines class A and function A::foo)
  • a.cpp (uses A)
  • b.cpp (uses A and A::foo)

Then during compilation of a.cpp, only A would be instantiated. However, during compilation of b.cpp, both would be instantiated.

Because of this, in case A::foo contained some semantically invalid code for a given set of template parameters, you would get compile errors in b.cpp, but not a.cpp.

I hope that clears things up!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...