gpt4 book ai didi

c++ - 如何检测是否将除整数以外的任何内容传递给我的类构造函数?

转载 作者:行者123 更新时间:2023-12-01 12:01:40 25 4
gpt4 key购买 nike

公平而简单:如何检查除整数以外的其他内容是否在C++中传递给我的类?

如果我通过我类的char 'a'以ascii编号。

我尝试了97,但是我不明白为什么它不检测整数:

#include <iostream>
#include <limits>

class integerCheck
{
public:
integerCheck(int value)
{
if((value != std::numeric_limits<int>::is_integer))
return;

std::cout << value << std::endl;
}
};

int main()
{
integerCheck valInt(88);
integerCheck valChar('a');
integerCheck valFloat(13.44f);

return 0;
}

我发现 this Post与 std::numeric_limits一起使用,但是我无法想象即使在c++ 20中也无法检测到错误的输入,而是将所有内容包装在模板中。

我缺少什么,我应该寻找/寻找什么才能检测到除整数以外的任何东西?
预先感谢

最佳答案

删除采用char的构造函数,并使ctor explicit阻止接收float,如下所示

class integerCheck
{
public:
explicit integerCheck(int value)
{

std::cout << value << std::endl;
}
integerCheck(char ) = delete;
};
这不允许以下两个ctor进行编译
integerCheck valChar('a');
integerCheck valFloat(13.44f);
我认为以下将更好地防止除 int之外的所有类型。
class integerCheck
{
public:
explicit integerCheck(int value)
{

std::cout << value << std::endl;
}

template<class T>
integerCheck(T ) = delete;
};
请注意,过去的代码不会阻止 longsize_tshort,...等整数类型的est。

关于c++ - 如何检测是否将除整数以外的任何内容传递给我的类构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62366202/

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