Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/153.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何自定义转换模板参数_C++_Templates - Fatal编程技术网

C++ 如何自定义转换模板参数

C++ 如何自定义转换模板参数,c++,templates,C++,Templates,假设我解析一个文件,得到一个字符串向量,它包含各种数据类型。我现在正在寻找一个函数,如: template<typename T> T convertToType(const std::string& str); 另一种选择是为每种类型编写模板专门化,但如果我必须再次为每种类型指定模板函数,这似乎会使模板函数的使用变得毫无用处……这将Joachim的评论变成一个答案 使用std::istringstream并让输入操作符>处理它 std::istringstream iss

假设我解析一个文件,得到一个字符串向量,它包含各种数据类型。我现在正在寻找一个函数,如:

template<typename T>
T convertToType(const std::string& str);
另一种选择是为每种类型编写模板专门化,但如果我必须再次为每种类型指定模板函数,这似乎会使模板函数的使用变得毫无用处……

这将Joachim的评论变成一个答案

使用
std::istringstream
并让输入操作符
>
处理它

std::istringstream iss(str);
T result;
if (!(iss >> result)) {
    throw std::logical_error("Type conversion failed!");
}
return result;

让输入操作符
>>
处理一个简单的问题怎么样?模板专门化呢?或者
boost::lexical\u cast
?因为用户定义的类型需要提供一个转换函数,我看不出要求用户提供转换专门化的问题。因此,为了支持新的/自定义类型,我只需定义std::istringstream&operator>>(std::istringstream&is,MyType&type)的友元重载即可?如果是,那么这正是我要找的。如果我的一个新类型没有实现这个操作符,编译时会有一个错误,对吗?
std::istringstream iss(str);
T result;
if (!(iss >> result)) {
    throw std::logical_error("Type conversion failed!");
}
return result;