Home Ask Login Register

Developers Planet

Your answer is one click away!

Kevin217 February 2016

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 (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);


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

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


BarryTheHatchet February 2016

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.

Post Status

Asked in February 2016
Viewed 2,493 times
Voted 9
Answered 1 times


Leave an answer

Quote of the day: live life