Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use assert to test type defintions in C++?

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;
}
like image 840
Elpezmuerto Avatar asked Sep 26 '11 18:09

Elpezmuerto


1 Answers

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.

like image 195
Tom Kerr Avatar answered Oct 04 '22 17:10

Tom Kerr