相关功能家族的通用功能(例如std :: stoi,std :: stof,std :: stod等)
Generic function for a family of related functions (e.g. std::stoi, std::stof, std::stod etc)
我想为std :: stoi,std :: stof,std,std :: stod等做一个通用功能。
// std::string -> int
std::string str = "1000000";
int i = to_numeric<int>(str);
// std::string -> long
std::string str = "100000000000";
long i = to_numeric<long>(str);
// std::string -> float
std::string str = "10000.1";
float i = to_numeric<float>(str);
,但我不知道如何使部分专业化:
template<class T>
int to_numeric(const std::string &str, size_t *pos = 0, int base = 10) {
return std::stol(str, pos, base);
};
template<>
long to_numeric<long>(const std::string &str, size_t *pos, base) {
return std::stol(str, pos, base);
};
template<>
float to_numeric<float>(const std::string &str, size_t *pos) {
return std::stof(str, pos);
};
// .....
错误:
to_numeric.cpp:76:79: error: default argument specified in explicit specialization [-fpermissive]
to_numeric.cpp:76:12: error: template-id 'to_numeric<float>' for 'float to_numeric(const string&, size_t*)' does not match any template declaration
make: *** [build] Error 1
您指定了一个主模板,该模板需要三个参数(str
,pos
和base
),但是您尝试使用只有一个参数的功能模板来对其进行专业化。显然,这行不通:专业需要匹配主模板。
功能模板的部分专业化不受[尚未支持吗?]。如果您需要部分专业的功能模板,则需要间接进行部分专业化:您将委派给类模板并部分专业化。类模板可能只有一个static
功能。当然,在您的示例中,您不使用部分专业化,而是完整的专业化。
首先,您必须使非专业模板函数完全模板。这意味着您必须制作返回类型T
。我还建议这种非特殊功能除了返回之外,任何事情都不会做任何其他事情,例如。T()
(因为它不是专业化的,并且不知道该调用什么功能)。
要继续,to_numeric<float>
专业化需要具有与非专业函数相同的参数,因此您需要添加虚拟base
参数。
相关文章:
- std ::功能作为默认参数的功能
- 复制std ::功能多么昂贵
- 将多种类型传递给STD ::功能C
- STD ::功能,字面类型和模板
- 使用STD ::功能时,编译器无法推断类型
- 调用STD ::功能,并带有变体类型列表
- STD ::功能的类型扣除额
- STD功能替换向量中的字节范围
- 如何管理STD ::功能的STD ::向量
- 绑定std ::功能错误
- 将成员函数和lambdas传递给std ::功能
- std ::功能和错误:无需匹配函数
- 如何通过C通过C API传递std ::功能
- 将std ::函数铸造到其他std ::功能并调用它
- 如何将std ::功能包装器转换为变异功能
- rvalue参考绑定到std ::功能类型的LVALUE
- lambdas不使用功能接受std ::功能
- 虚拟方法与std ::功能成员变量在性能方面
- sTD ::功能的替代方案,用于收集可可的功能
- 为什么不能将std :: stol转换为std ::功能对象