gpt4 book ai didi

c++ - 检查 "is int"/"is double"/etc 的模板函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:25:00 24 4
gpt4 key购买 nike

我不太了解 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:

最佳答案

我对你的帖子的评论经受住了考验,轻松做到这一点的方法是使用一个简单的模板,该模板使用 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 >>

关于c++ - 检查 "is int"/"is double"/etc 的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45206838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com