Consider a container A
holding some data:
template<typename T>
struct A
{
std::vector<T> data;
};
Inside, I will only store raw pointers, either const or not. Say:
A<int*> a1;
A<const int*> a2;
Now I need a member function that will return a reference on an element, because although I store pointers, I want the client code to use references (safer):
int& b1 = a1.GetElem(0);
const int& b2 = a2.GetElem(0);
My question is: how do I get either a T&
or const T&
from that member function, depending on the stored elements.
What I have tried is to remove the pointer type, then add the reference:
std::add_lvalue_reference< std::remove_pointer<T>::type >::type
GetElem<T>( int i )
{
return *data[i];
}
But this does not compile:
error: type/value mismatch at argument 1 in template parameter list for ‘template<class _Tp> struct std::add_lvalue_reference’
note: expected a type, got ‘std::remove_pointer<T>::type’
I also tried to use a typedef in my class, but this fails too:
typedef std::remove_pointer<typename T>::type T2;
Is there any way I can do that ?
Edit: The linked question asks about general advice on the usage of the typename
keyword, while this one is about the specific problem of conversion between pointer type to reference type. This is reflected by the titles of the two questions, that are completely unrelated.
Moreover, the linked question is only relevant to solve the given sample code error, but provides no solution to the question. If I hadn't given a code snippet, it would have never been classified as a dupe.