我想为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
参数。