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
306 views
in Technique[技术] by (71.8m points)

c++ - Copy constructor of template class

I read that template copy-con is never default copy onstructor, and template assignment-op is never a copy assignment operator.

I couldn't understand why this restriction is needed and straight away went online to ideone and return a test program but here copy constructor never gets called on further googling I came across templatized constructor and tried that but still it never calls copy constructor.

#include <iostream>
using namespace std;

template <typename T> class tt
{
    public :
    tt()
    {
        std::cout << std::endl << "   CONSTRUCTOR" << std::endl;
    }
    template <typename U> const tt<T>& operator=(const tt<U>& that){std::cout << std::endl << "   OPERATOR" << std::endl;}
    template <typename U> tt(const tt<U>& that)
    {
        std::cout << std::endl << "    COPY CONSTRUCTOR" << std::endl;
    }
};


tt<int> test(void)
{
    std::cout << std::endl << "      INSIDE " << std::endl; tt<int> a; return a;
}

int main() {
    // your code goes here
    tt<int> a ; a = test();

    return 0;
}

Can someone explain me the whole reason behind putting this restriction and also how to write a copy constructor of template class.

Thanks

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

I can't comment on why this is how it is, but here's how you write a copy constructor and assignment operator for a class template:

    template <class T>
    class A
    {
      public:
        A(const A &){}
        A & operator=(const A& a){return *this;}
    };

and that's it.
The trick here is that even though A is a template, when you refer to it inside the class as A (such as in the function signatures) it is treated as the full type A<T>.


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

...