Re: Confirm Template if correct
On 3/2/2011 7:04 PM, Nephi Immortal wrote:
Please confirm if I am correct.
If you assign ?unsigned char? to typename T, then T data is
translated to unsigned char data as passing copy value.
If you assign ?unsigned char&? to typename T, then T data is
translated to unsigned char&data as passing reference.
First off, there is no 'T' in your code. If you're talking about a
template like this one:
template<class T> class TT { T data; };
then yes, the member 'data' has the type 'unsigned char' if you
instantiate 'TT' with 'unsigned char' and has the type 'unsigned char&'
if you instantiate 'TT' with 'unsigned char&'. Is that what you need to
confirm?
template< typename L, typename R>
class X {
public:
X< L, R>( L data ) : m_data( data ) {
}
X< L, R> &operator=( R data ) {
m_data = data;
return *this;
}
L m_data;
};
typedef unsigned char size_8;
int main () {
size_8 data = 0x34U;
const X< size_8, size_8> A( 0x12U ); // constant
X< size_8&, size_8> B( data ); // reference
A.m_data++; // error cannot modify left value because of constant
class
The 'A.m_data' has a value type. Since 'A' is const, 'A.m_data' value
is also const.
B.m_data++; // can modify non-constant class
The 'B.m_data' is a reference type (referencing a non-const object of
type 'unsigned char'. Even if you define 'B' as const, you should be
able to modify the object to which 'B.m_data' refers. Try declaring 'B'
const.
return 0;
}
V
--
I do not respond to top-posted replies, please don't ask