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;
}
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.
#include <boost/static_assert.hpp>
#include <boost/type_traits.hpp>
template<typename T>
void some_func() {
BOOST_STATIC_ASSERT( (boost::is_same<double, T>::value) );
}
TEST(type_check) {
some_func<double>();
}
I assume you mean in terms of a template anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With