I was wondering if I write something like this:
Type &var = database.get<TYPE>(name);
Assuming that database
is a container able to store datablocks of different datatypes. To get a reference to that datablock, the name
as std::string
is passed to get() so that at different places with that call I have a way to access certain 'global' variables. I have get() as a template method and I would like to keep it that way.
What I want to do is shorten that call an elegant way like this:
Type &var = database.get(name);
So the template deduction is automatically performed. Now I could create a macro for that, but this is not what I want to do, as I do not consider it elegant for such case.
That deduction though does not work, because we need a template parameter. Why can't the compiler take what is set for the variable and pass it as template parameter automatically? Is there a way to do this? I don't want to have any type conversions in this case. Can we omit it?
No, you can't do this---the rules of the language simply don't allow the compiler to take into account the declared type of var
in order to perform the deduction. (Note that template arguments for a function template can be deduced when initializing a function pointer by taking the address of a function template. However, that's not what's happening in this case.)
However, you can easily avoid writing the type twice or inducing any undesirable conversions, by using auto
:
auto& var = database.get<Type>(name);