Templates and structures

A

AMT2K5

template <class TYPE>
struct HashEntry{
TYPE rec_;
const char* key() const{
//something
}
};

If I know that any datatype TYPE will always have a private member
"key", how can I return rec_'s key in the key() function?
 
G

Gianni Mariani

AMT2K5 said:
template <class TYPE>
struct HashEntry{
TYPE rec_;
const char* key() const{
//something
}
};

If I know that any datatype TYPE will always have a private member
"key", how can I return rec_'s key in the key() function?

template <class TYPE>
struct HashEntry{
TYPE rec_;
const char* key() const{
return rec_.key;
}
};

You need to make sure that TYPE has "HashEntry" as a friend class. i.e.

template <class TYPE> friend struct HashEntry;
 
I

IR

Gianni said:
template <class TYPE>
struct HashEntry{
TYPE rec_;
const char* key() const{
return rec_.key;
}
};

You need to make sure that TYPE has "HashEntry" as a friend class.
i.e.

template <class TYPE> friend struct HashEntry;

Requiring any TYPE to have HashEntry<TYPE> as a friend should IMO be
avoided when possible.

Here it can be avoided, by calling a public const accessor
rec_.get_key() instead of accessing the private member key.


class MyType
{
public:
const char* get_key() const { return key; /* or whatever */ };
private:
const char* key;
};

template <class TYPE>
struct HashEntry
{
TYPE rec_;
const char* key() const { return rec_.get_key(); };
};
 

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,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top