when a const isn't? (typedef?)

T

Tim H

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;
}
 
K

kwikius

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 said:
::type const_reference;

(not tested)

regards
Andy Little
 

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,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top