0

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?

asked Feb 9, 2016 at 0:05

1 Answer 1

4

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.

answered Feb 9, 2016 at 0:06
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.