公平而简单:如何在 c++ 中检查除了整数之外的其他内容是否传递给我的类?
如果我通过 f.e. achar 'a'
我的班级在 ascii 中排名第97
。
我试过std::numeric_limits
但我不明白为什么它没有检测到整数:
#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;
}
我发现这篇文章适用于std::enable_if
但我无法想象即使在 c++20 中也无法检测到错误的输入,而是将所有内容包装在模板中。
我错过了什么,我应该查找/搜索什么来检测除整数值以外的任何内容?提前致谢
删除取char
s 的构造函数,并使 ctorexplicit
以防止接受float
s,如下所示
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;
};
请注意,过去的代码不会阻止 est 的整数类型,如long
、size_t
、short
、...
构造函数只接受int
值作为输入。char
是整型类型,因此它可以隐式转换为int
。浮点类型也是如此。
而且你对std::numeric_limits<T>::is_integer
的使用不起作用,因为当T
int
时,就像你在硬编码一样。但对于其他积分类型也是如此,包括char
.
如果要避免隐式转换,可以通过非常量引用传递int
,例如
integerCheck(int &value) {
std::cout << value << std::endl;
}
但是,这意味着您也不能传入整数文本。仅int
变量。
更好的解决方案是让integerCheck()
使用模板参数,然后可以检查编译器从输入中推断出的模板类型,例如:
#include <type_traits>
template<typename T>
integerCheck(const T &value) {
if constexpr (std::is_same_v<T, int>) {
std::cout << value << std::endl;
}
}
integerCheck valInt(88); // T=int
integerCheck valChar('a'); // T=char
integerCheck valFloat(13.44f); // T=float
也许是这样的
:class integerCheck
{
public:
// Arguments of type other than `int` go here.
template <typename T>
integerCheck(T) {}
integerCheck(int value) {
std::cout << value << std::endl;
}
};