简体   繁体   中英

C++ - Define Copy Constructor in Template

I'm a beginner in template coding, and having trouble defining constructor in template, and just looked for answers about that but cannot find related questions.

Basically the class/struct xpair is similar to pair which has first and second .

template <typename First, typename Second>
struct xpair {
   First first{};
   Second second{};

   xpair(){}
   xpair (const First& first, const Second& second):
              first(first), second(second) {}

   xpair& operator() (const First& first_, const Second& second_) {
      return new xpair (first_, second_);
   }

   xpair& operator= (const xpair& that) {
      return new xpair (that.first, that.second);
   }
};

When I'm trying to write something like

xpair<string, string> a, b;
a = b;

It gives error as

non-const lvalue reference to type
'xpair<std::__1::basic_string<char>, std::__1::basic_string<char> >'
cannot bind to a temporary of type 'xpair<std::__1::basic_string<char>,
std::__1::basic_string<char> > *'

I tried rewrite

return new xpair (that.first, that.second);

to

return new pair (const_cast<First&>(that.first), const_cast<First&>(that.second));

But it doesn't work. Where's the problem?

Drop the new . This isn't Java!

In C++, new is the keyword for dynamic allocation (evaluating to a pointer), which you're not using.

You'll also have to rethink your return-by-reference semantics as you'll be returning a reference to a local variable. That makes a dangling reference.

In fact your semantics look bizarre to me overall. For example, why does operator= not actually modify the object being assigned to? You should assign from that to *this 's members then return a reference to *this (or, at least, return void ).

And I can't tell what your operator() is supposed to do — should that be a constructor instead? Hmm, no, you already have one of those… :(

I strongly recommend taking a look at some examples of operator overloading to gain a better understanding not only of C++'s constructs and constraints, but also our idioms and preferred semantics.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM