Any good way to extend std::swap?

S

Sung Jin Hwang

Hi.

Is there a good way to extend std::swap to user type classes?
Overloading can be a solution but when user type is not a
class but class template, we need partial specialization and
function partial specialization is not allowed.

What I can easily think about is to define a function in the
namespace which contains the user type but this forces to
use a namespace (well... though it is better to use namespaces)
and C++ symbol lookup rules becomes complex for some
cases and it is not fool-proof. Furthermore, it forces me to
use such redundancies when I wish to use std::swap.

{
using std::swap;
swap(A, B);
}

Is there any better suggestions for this?


By the way, is there any attemp to add an operator or
re-use an operator in C++ so that swap becomes a built-in
operator operation?

Swap or exchange is quite essential concept in computer
science and it is quite frustrating that using and implementing
swap operations is that tricky. In addition, touching and
modifying something that is in std namespace always makes
me frown and feel guilty.

Why don't we allocate an operator for swap operation
and let the compiler generate default code like assignment
operator? I sometimes think that it would be nice if colon
operator does this thing, though this will introduce ambiguity
in parsing when used with label feature.
 
R

red floyd

Sung said:
Hi.

Is there a good way to extend std::swap to user type classes?
Overloading can be a solution but when user type is not a
class but class template, we need partial specialization and
function partial specialization is not allowed.

There's a description in full gory detail in "C++ Template Metaprogramming".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top