Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: C++
Expertise: Beginner
Jun 6, 1997



Application Security Testing: An Integral Part of DevOps

Template functions in classes

Can I overload the >> operator in a class for all integral types using a template? If so, how?

The short answer is no.

The long answer?

Templates are mechanisms for providing generic behavior for a range of types. There is no way in C++ to directly restrict the types that can be passed in. There are some tricks that can be used to restrict certain usages, like situations in which the only types that will be allowed are those that derive from some class X. Here is an example of how to do that:

class AllowOnlyXandDerivedClasses
     T *t;
     X *x = t; // this will generate a compiler error for
               // types other than X and its derived classes.
By extending the same concept, you could try something for integral types.
X &operator << (X const&x, T t)
   int i = t; // should fail for _MOST_ non-integral types.
   // .. rest
  return x;
Although this looks promising, it will also allow classes for which conversion operators or non-explicit constructors exist, so the solution is not foolproof.
DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date