c++ - Converting between types in function templates -


i have function template gives result reference variable defined template. function must convert value , assign reference variable. have problem compiling in line show in code.

what wrong , how can solve that?

the following code:

#include "stdafx.h" #include <iostream> #include <string> #include <map>  using namespace std;  map<wstring, wstring> my_data = {     { l"data1", l"123.456"  },     { l"data2", l"2213.323" },     { l"data3", l"3321.321" },     { l"data4", l"1000" },     { l"data5", l"2000" } };    template<class t> bool get_map_value(const wstring &map_key, t& map_value) {     auto tmp = my_data.find(map_key);      if (tmp == my_data.end())         return false;      if (typeid(t).name() == typeid(wstring).name())         map_value = tmp->second;         //error c2440   '=': cannot convert 'std::wstring' 'int'             //error c2440   '=': cannot convert 'std::wstring' 'double'       else if (typeid(t).name() == typeid(double).name())         map_value = _wtof(tmp->second.c_str());      else if (typeid(t).name() == typeid(int).name())         map_value = _wtoi(tmp->second.c_str());       return true; }   int main() {      double d = 0.0;     wstring w = l"";     int = 0;      get_map_value(l"data1", w);     get_map_value(l"data3", d);     get_map_value(l"data4", i);       return 0; } 

what wrong

the type of tmp->second wstring. when template instantiated t = int, type of map_value int&. line

map_value = tmp->second; 

has pretty self explanatory error message

error c2440   '=': cannot convert 'std::wstring' 'int' 

std::wstring not implicitly convertible int. problem. must remember entire function must formed, if execution cannot reach part of it.


how can solve that?

what need few overloads. shall refactor differing part of function, don't need repeat identical part.

parse_value(int& variable, const std::wstring& value) {     variable = _wtoi(tmp->second.c_str()); } parse_value(double& variable, const std::wstring& value) {     variable = _wtof(tmp->second.c_str()); } parse_value(std::wstring& variable, const std::wstring& value) {     variable = value; }  template<class t> bool get_map_value(const wstring &map_key, t& map_value) {     auto tmp = my_data.find(map_key);      if (tmp == my_data.end())         return false;      parse_value(map_value, tmp->second);      return true; 

}


Comments