I'm changing the title of the topic into "Questions about Templates" because I'm experimenting with it and I know I will have more than one, doesn't seems right to make 1000 mini-topics
So now I have the code below:
template<typename T>
struct S
{
S(T v) :val{ v } {};
T val;
};
template <typename R, typename T>
R& get(T& e)
{
return e.val;
}
int main()
{
S<char> MySChar('B');
cout << "MySChar: " << MySChar.val << endl;
cout << "Returned val: " << get<char>(MySChar) << endl;
return 0;
}
The function get is not part of the S class, as required from the book exercise (which is "" Add a function template get() that returns a reference to val.")
I don't like that I have to specify the return type when I call it, if I have 5 different instantiation of S it becomes messy, so I was trying to make it in such a way that I can just write get(MySChar) and it just works with wathever instantiation of S, but I am failing on it, code below:
template<typename T>
struct S
{
S(T v) :val{ v } {};
T val;
typedef T type;
};
template <typename T, typename R>
R& get(T& e)
{
using R = e.type;
return e.val;
}
int main()
{
S<char> MySChar('B');
cout << "MySChar: " << MySChar.val << endl;
cout << "Returned val: " << get(MySChar) << endl;
return 0;
}
How would I do that the proper way?