By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,952 Members | 1,424 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,952 IT Pros & Developers. It's quick & easy.

template specialization for unsigned types

P: 2
Hello all,

First, some mostly gratuitous background, which you can safely skip if you're not interested, or feel free to comment/give suggestions:
I am writing a configuration interface for a DAQ system which reads in text-based configuration files. Because of the large number of parameters which might need to be set and their grouping into a nice tree-like structure, I've created a ParameterNode class, which holds a map<string,ParameterNode*> of all that node's children (or branches, leaves, whatever). Then to store simple variables, there is a templated Parameter<class T> class which inherits from ParameterNode. This allows me to have arbitrarily complex parameter structures without having to re-write any of the iostream interface.

So here's the problem. My Parameter class looks like
Expand|Select|Wrap|Line Numbers
  1. template<class T> Parameter{
  2. public:
  3.      Parameter(const T& val) : _val(T) {}
  4.      ~Parameter() {}
  5.      std::istream& ReadFrom(std::istream& in) { return in>>_val; }
  6.      std::ostream& WriteTo(std::ostream& out) { return out<<_val; }
  7. private:
  8.      T _val;
  9. };
  10.  
Now, I'd like to have any unsigned values be written/read with the form 0x1EF8, etc, i.e. turn on hex and showbase. So for instance I'd get something like

Expand|Select|Wrap|Line Numbers
  1. template<> inline std::istream& Parameter<unsigned>::ReadFrom(std::istream& in)
  2. {
  3.   in>>std::hex>>std::showbase>>_val>>std::noshowbase>>std::dec;
  4. }
So, will this work for any unsigned type, or do I have to declare separate instantiations for all of unsigned, unsigned char, unsigned short, unsigned long, uintX_t, etc?

Many thanks,
~Ben
Nov 3 '08 #1
Share this Question
Share on Google+
2 Replies


100+
P: 424
"unsigned" is a synonym for "unsigned int" so yes you'll have so specify the different specializations explicitly if you want different behavior from signed types, or just don't specialize if it's all the same anyway. You might want to take a look at boost traits which you can use to determine if a type is unsigned.
Nov 4 '08 #2

P: 2
Thanks! Is there anything Boost can't do? Unfortunately I'm trying to minimize dependencies, so I don't want to include Boost. I noticed that the type_traits headers are also in the tr1 package which should be on most systems, but it doesn't seem to want to compile (well actually it's only linking that's the problem) on my system.

Oh well, I guess specifying them all by hand is is not so bad.
Nov 4 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.