首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查"is int"/"is is/etc“的模板函数

检查"is int"/"is is/etc“的模板函数
EN

Stack Overflow用户
提问于 2017-07-20 06:29:44
回答 2查看 100关注 0票数 1

对于C++模板语法,我有点犹豫,所以我不确定我设想的是什么,如果是的话,我不清楚正确的语法。

我想实现像template<int> bool is( std::string& )template<double> bool is( std::string& )等模板函数,这样我就可以调用is <int> (...)is <double> (...)而不是isInt(...)isDouble(...)等等。这可能吗?如果是这样,您将如何编码函数签名?

由于我对模板语法的掌握有限,我的尝试是:

代码语言:javascript
复制
#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;
}

如果出现以下错误,此操作失败:

代码语言:javascript
复制
>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:
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-07-20 06:41:16

对于您的帖子,我的评论是,使用一个使用std::istringstream类来解析的简单模板可以轻松地做到这一点:

代码语言:javascript
复制
template<typename T>
bool is(std::string const& raw) {
  std::istringstream parser(raw);

  T t; parser >> t;
  return !parser.fail() && parser.eof();
}

显而易见的警告是,T必须是默认的可构造的。但从好的方面来说,只要用户定义的类型实现了operator >>,上面的内容也同样适用。

票数 6
EN

Stack Overflow用户

发布于 2017-07-20 06:41:02

为此,您需要使用模板专门化:

代码语言:javascript
复制
#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;
}

您可以在这里中阅读更多有关信息。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45206838

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档