How to use pass-by-reference arguments of a template type in method templates?

I am currently trying to compile the following code. First, a header file containing a class with a method template:

// ConfigurationContext.h class ConfigurationContext { public: template<typename T> T getValue(const std::string& name, T& default) const { ... } } 

Somewhere else I want to call this method as follows:

 int value = context.getValue<int>("foo", 5); 

There I get the following error:

 error: no matching function for call to 'ConfigurationContext::getValue(const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&, int)' 

I checked for obvious errors, such as the absence of includes and the like. But everything seems right. I tried to remove the pass-by-reference template type argument as follows:

 template<typename T> T getValue(const std::string& name, T default) const ... 

Then it compiles without any errors and also works fine, but I would still like to pass the link here ...

Does anyone know what is going on here and how to do it?

0
source share
1 answer

5 is a literal, and you cannot bind literals to const links. Either take T for a copy, or for a const link:

 template<typename T> T getValue(const std::string& name, const T& def) const 

(BTW, I doubt your compiler accepts T default because default is a keyword and should not be used as an identifier.)

The reason you cannot do this is because using arguments for a reference other than const usually implies that the caller can change the value, and such changes should affect the caller. (See How to pass objects to functions in C ++? ) However, you cannot modify literals or temporary files. Therefore, you are not allowed to pass them to const links.

+5
source

All Articles