对于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;
}如果出现以下错误,此操作失败:
>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:发布于 2017-07-20 06:41:16
对于您的帖子,我的评论是,使用一个使用std::istringstream类来解析的简单模板可以轻松地做到这一点:
template<typename T>
bool is(std::string const& raw) {
std::istringstream parser(raw);
T t; parser >> t;
return !parser.fail() && parser.eof();
}显而易见的警告是,T必须是默认的可构造的。但从好的方面来说,只要用户定义的类型实现了operator >>,上面的内容也同样适用。
发布于 2017-07-20 06:41:02
为此,您需要使用模板专门化:
#include <iostream>
#include <cstdlib>
template<class T> bool is(std::string& raw) = delete;
template<>
bool is<int>( 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;
}您可以在这里中阅读更多有关信息。
https://stackoverflow.com/questions/45206838
复制相似问题