|
-
August 1st, 2008, 02:24 AM
#1
Partial const on struct
Hi. I have a problem with const data types. I have a template structure named pair
Code:
template <class K, class V>
struct pair
{
K key;
V value;
pair() : key(), value() {}
pair( K const& k, V const& v ) : key(k), value(v) {}
};
Then, I wanted to declare a variable where only 'key' member is constant. So I wrote
Code:
pair<int const, int> X;
The problem is, I can't assign pair<int, int> to that variable. So I changed the structure like this
Code:
template <class K, class V>
struct pair
{
K key;
V value;
pair() : key(), value() {}
pair( K const& k, V const& v ) : key(k), value(v) {}
operator pair<K const, V> const& () const
{ return *reinterpret_cast<pair<K const, V> const*>(this); }
operator pair<K const, V>& ()
{ return *reinterpret_cast<pair<K const, V>*>(this); }
};
pair<int, int> P;
pair<int const, int>& X = P; // Now I can do this
My question is : Is this regular way? And if not, what would be better? So far I tried to avoid reinterpret_cast as long as possible.
Any information would be much appreciated.
Thanks
I'd really be happy if C++ had template typedefs and void references, like void& / void const&.
When I program, I type, type, type... and eventually delete everything as my code contains buckets of bugs.
OMG so I'm programming to make bugs?
I'm happy when I meet someone who doesn't agree with me, because I can learn a lot by talking to him/her.
"Genius is one percent inspiration and ninety-nine percent perspiration." Thomas Edison
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|