c++ - 在函数模板中的类型之间转换

标签 c++

我有一个函数模板,它通过模板定义的引用变量给出结果。 此函数必须转换一个值并分配给引用变量。 我在代码中显示的行中进行编译时遇到问题。

出了什么问题,我该如何解决?

以下是我的代码:

#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 from 'std::wstring' to 'int'    
        //Error C2440   '=': cannot convert from 'std::wstring' to '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 i = 0;

    get_map_value(L"data1", w);
    get_map_value(L"data3", d);
    get_map_value(L"data4", i);


    return 0;
}

最佳答案

What is wrong

tmp->second 的类型是wstring。当使用T = int 实例化模板时,map_value 的类型为int&。线路

map_value = tmp->second;

有非常 self 解释的错误信息

Error C2440   '=': cannot convert from 'std::wstring' to 'int'

std::wstring 不能隐式转换为 int。那就是问题所在。您必须记住,整个函数必须格式正确,即使执行无法到达其中的某些部分。


how can I solve that?

您只需要一些重载。我们将重构功能的不同部分,这样您就不需要重复相同的部分。

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;

关于c++ - 在函数模板中的类型之间转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38508079/

相关文章:

c++ - 将 vector<T> 转换为 vector<const T>

c++ - Visual Studio 2010 - 排除文件类型

C++ 控制台应用程序 MVC

c++ - Visual Studio 是否具有命名空间敏感的宏替换选项?

c++ - 在C++中初始化一个二维对象数组

c++ - 用 `alglib::integer_1d_array` 创建 `Eigen::Matrix`

c++ - 为什么逗号运算符在运算符 [] 中被调用,而不是在运算符 () 中?

c++ - 跟踪 C++ 内存分配

c++ - 如何删除 "Ctrl + Backspace"特殊字符?

c++ - boost.mpi 中的自定义 reduce 操作