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

when a const isn't? (typedef?)

P: n/a
How come this behaves the way it does? val_D() and val_E() cause a
(correct) compiler error. val_F() and val_G() do not, but I don't see
why.

Can anyone enlighten me?
#include <iostream>
using namespace std;

class foo {
public:
typedef int value_type;
typedef value_type& reference;
typedef const reference const_reference;

explicit foo(int x): m_val(x) {}

int val() { return m_val; }

int& val_A() { return m_val; }
value_type& val_B() { return m_val; }
reference val_C() { return m_val; }

const int& val_D() { return m_val; }
const value_type& val_E() { return m_val; }
const reference val_F() { return m_val; }
const_reference val_G() { return m_val; }

private:
int m_val;
};

int main()
{
foo x(0);

cout << x.val() << endl;
x.val_A() = 1;
x.val_B() = 2;
x.val_C() = 3;
x.val_D() = 4; // compile error
x.val_E() = 5; // compile error
x.val_F() = 6;
x.val_G() = 7;
cout << x.val() << endl;

return 0;
}

Mar 19 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
On 19 Mar, 03:25, "Tim H" <thoc...@gmail.comwrote:
How come this behaves the way it does?
<...>

At this point below you are attempting to apply constness to a
reference which has no effect. constness can only affect actual
objects if you get my meaning...
typedef const reference const_reference;
VC7.1 gives:

d:\Projects\Test\Test.cpp(10) : warning C4181: qualifier applied to
reference type; ignored

Similarly when used in the function return later...

The generic way to approach adding const to references is to use
typetraits:
(boost or std::tr1)

First remove any refernce, then add const then ree-add reference
where T is some type
typedef typename add_reference<
typename add_const< typename remove_reference<T>::type>::type
>::type const_reference;
(not tested)

regards
Andy Little

Mar 19 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.