Restricting template parameters to signed or unsigned types, but notboth

D

Damian

Hi there,

I would like to restrict a template parameter to a template functioned
to either a signed or unsigned type, but not both.

For example, the following templated function should ideally only be
instantiated with unsigned types.

template <typename unsigned T>
inline T id(T *i) {
return i;
}

void foo() {
(void)id<int>(k); // should return an error.
(void)id<unsigned int>(k); // should be fine.
}

Does anyone know how I can achieve this?

Thanks!

Best Regards,

Damian Eads
 
D

Damian

I don't know what algorithm you are indending to implement (your
example is contrived and invalid).

Err, I meant

template class <typename T> // How do I reflect the signedness or
unsignedness restriction here?
inline T id(T i) {
return i;
}

It is contrived. I don't think it's important for you to see the
algorithm. I want to know how to restrict the signedness of templates
in the general case. I have found that when I post specifics about the
algorithm, people focus their comments on the algorithm, when I'm
interested in entirely something else.
The general way is to just accept unqualified T but apply a

I didn't quite get that. Please resend.

Thanks,

Damian
 
D

Damian

Often enough we see folks asking "how do I <whatever>" thinking that
it would solve some problem they allegedly have, while the actual
solution to what's holding them from an acceptable result is nothing
close. That is why sometimes, especially if the solution isn't at
all an easy one, we might need proof (to ourselves) that we're not
spending time solving the problem that you don't actually have.

There is nothing personal here, please understand.

Not taking anything personally. I understand list traffic frequently
deals with questions about algorithms. However, while I am sure many
of this groups' members are quite skilled in algorithms, it is not
typically what I would come to a C++ list for.

Really what I am interested in how to restrict template arguments on
signedness as well as base class. It looks like boost has some
sophisticated template tools so I will look into them more deeply.
Thanks for bringing them to my attention.
As to your particular inquiry, you should probably look into Boost's
"enable_if" template and type traits, so you could "enable if your
type T has a trait of being of the unsigned [integral] variety".

Thanks. I will look into enable_if construct in Boost.

Damian
 

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,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top