我可以使用 assert 来强制执行类型定义吗?假设有一个变量,double d
,如何使用assert
来断言d是一个double?如果 assert
不适用(我打赌不适用),还有其他选择吗?我特别希望在调试期间测试隐式类型转换,同时受益于 assert
和 #define NDEBUG
的功能。
聚苯乙烯
显然我想将其用于任何类型定义,这里仅使用 double 作为示例。该解决方案应该是跨平台兼容的并且与C++03兼容。
我喜欢为我的类设置器添加错误检查。例如,假设有一个类 MyClass,它有一个私有成员变量 x:
void MyClass::setX(double input)
{
// assert x is double
x = input;
}
Can I use assert to enforce type definitions. Suppose there is a variable, double d
, how can you use assert
to assert that d is a double? If assert
is not applicable (which I am betting isn't), is there another option? I am specifically looking to test for implicit type casting during debugging, while benefiting from the functionality of assert
and #define NDEBUG
.
P.S
Obviously I would want to use this for any type definition, just using double as an example here. The solution should be cross platform compatible and be compatible with C++03.
I like to add error checking to my class setters. For example, suppose there is a class, MyClass, with a private member variable, x:
void MyClass::setX(double input)
{
// assert x is double
x = input;
}
发布评论
评论(5)
这实际上是一个编译时检查,因此您应该为此使用静态断言。
这是一个使用 boost 的静态断言和类型特征的示例。
无论如何,我认为您的意思是模板。
It's really a compile time check, so you should use static asserts for this.
Here is an example using boost's static asserts and type traits.
I assume you mean in terms of a template anyway.
您可以使用
type_info
== 运算符="nofollow noreferrer">class 用于测试特定类型定义。或者借用另一个使用模板和 try/catch 的 SO 答案:
You can use the
==
operator defined in thetype_info
class to test for a specific type definition.Or borrowing from another SO answer using templates and try/catch:
您应该能够使用
std::is_same
和使用decltype
进行比较。您甚至可以使用 std::static_assert 将检查移至编译时。我已经在 libc++ 中看到过这种情况 :)请注意,这些是 C++11 功能,因此您需要有一个支持
decltype
的编译器You should be able to compare using
std::is_same
and usingdecltype
. You can even usestd::static_assert
to move the check to compile time. I've seen it happen in libc++ :)Note these are C++11 features, so you'll need to have a compiler that supports
decltype
给定代码的当前定义,在编译时检查两者是否属于同一类型的方法是:
Given the current definition of the code, a way to check at compile time whether both are of the same type is:
您可以创建一个模板函数,然后重载
double
的参数类型,如下所示:这会产生运行时错误。您可以通过简单地定义一个采用双重引用的函数来生成编译时错误:
You can create a template function, then overload the argument type for
double
like this:That would give a run-time error. You can generate a compile time error by simply defining a function that takes a double reference: