Question

I currently have a database class with a few unordered maps containing the databases variables. I have written functions for adding and deleting variables but now want a way to access and modify them easily.

My function is like this:

template<typename T>
T &get(const  std::string &name){
    if(typeid(T) == typeid(int))
        return this->ints[name];
    else if(typeid(T) == typeid(float))
        return this->floats[name];

     ... ect ...
}

And throws an error if an invalid type is given.

ints is type std::unordered_map<std::string, int> and floats is defined likewise.

This, to me, looks correct. But when I try and run this I get the following error:

database.hpp:98: error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'

Looks like the unordered map isn't returning a reference, what is the issue?

Was it helpful?

Solution

Unline C# and Java generics, C++ templates can be specialized. Testing types the way you are doing is strongly discouraged.

If you used specialization, you wouldn't be having this problem, as it's related to conversions as BartoszKP commented.

template<typename T>
T& get(const std::string &name);

and outside the class, but still inside the header:

template<>
int& ClassName::get<int>(const std::string &name) { return ints[name]; }

template<>
float& ClassName::get<float>(const std::string &name) { return floats[name]; }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top