我对C++模板语法有点不稳定,所以我不确定我想象的是否可能,如果是,我不清楚正确的语法.
我想实现模板函数,如template<int> bool is( std::string& ),template<double> bool is( std::string& )等,以便我可以调用is <int> (...)或is <double> (...)代替isInt(...)或isDouble(...)等等.这可能吗?如果是这样,您将如何编写功能签名?
由于我对模板语法的掌握很少,我的尝试是:
#include <iostream>
#include <cstdlib>
template<int>
bool is( std::string& raw )
{
if ( raw.empty() ) return false;
char* p;
int num = strtol( raw.c_str(), &p, 10);
return ( ( *p != '\0' ) ? false : true );
}
int main( int argc, char* argv[] )
{
std::string str("42");
std::cout << std::boolalpha << is <int> ( str ) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
此操作失败,并出现以下错误:
>g++ -g main.cpp
main.cpp: In function ‘int main(int, char**)’:
main.cpp:16:51: error: no matching function for call to ‘is(std::string&)’
std::cout << std::boolalpha << is <int> ( str ) << std::endl;
^
main.cpp:5:6: note: candidate: template<int <anonymous> > bool is(std::string&)
bool is( std::string& raw )
^
main.cpp:5:6: note: template argument deduction/substitution failed:
Run Code Online (Sandbox Code Playgroud)
我对你的帖子的评论很容易,这样做的方法是使用一个简单的模板来使用std::istringstream该类进行解析:
template<typename T>
bool is(std::string const& raw) {
std::istringstream parser(raw);
T t; parser >> t;
return !parser.fail() && parser.eof();
}
Run Code Online (Sandbox Code Playgroud)
显而易见的警告是T必须是默认构造的.但从好的方面来说,只要它们实现,上述内容也适用于用户定义的类型operator >>.