可以在c++中使用assert来测试类型定义吗?

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

本文关键字:测试类 测试 类型 定义 assert c++      更新时间:2023-10-16

可以使用assert来强制类型定义吗?假设有一个变量,double d,你怎么用assert来断言d是双精度?如果assert不适用(我打赌不是),还有其他选择吗?我特别希望在调试期间测试隐式类型转换,同时受益于assert#define NDEBUG的功能。

p。年代显然,我想在任何类型定义中使用这个,这里只使用double作为例子。该解决方案应该是跨平台兼容的,并与c++ 03兼容。

我喜欢在我的类设置器中添加错误检查。例如,假设有一个类MyClass,它有一个私有成员变量x:

void MyClass::setX(double input)
{
   // assert x is double
   x = input;
}

这实际上是一个编译时检查,因此您应该使用静态断言。

下面是一个使用boost的静态断言和类型特征的例子:

#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>();
}

我想你是指模板。

您可以使用type_info类中定义的==操作符来测试特定的类型定义。

#include <assert.h>
#include <iostream>
#include <typeinfo>
int main ()
{
    double a = 0;
    std::cout << typeid(a).name() << std::endl;
    assert(typeid(a)==typeid(double));
    assert(typeid(a)==typeid(int)); // FAIL
}

或借用另一个SO答案使用模板和try/catch:

#include <assert.h>
#include <iostream>
#include <typeinfo>
template <typename X, typename A>
inline void Assert(A assertion)
{
    if( !assertion ) throw X();
}
#ifdef NDEBUG
    const bool CHECK_ASSERT = false;
#else
    const bool CHECK_ASSERT = true;
#endif
struct Wrong { };
int main ()
{
    double a = 0;
    std::cout << typeid(a).name() << std::endl;
    assert(typeid(a)==typeid(double));
    Assert<Wrong>(!CHECK_ASSERT || typeid(a)==typeid(double));
    try
    {
    //assert(typeid(a)==typeid(int)); // FAIL and Abort()
        Assert<Wrong>(!CHECK_ASSERT || typeid(a)==typeid(int)); // FALL
    }
    catch (Wrong)
    {
        std::cerr <<"Exception, not an int" <<std::endl;
    }
}

您应该能够比较使用std::is_same和使用decltype。您甚至可以使用std::static_assert将检查移到编译时。我在libc++中见过这种情况:)

注意这些都是c++ 11的特性,所以你需要一个支持decltype的编译器

给定代码的当前定义,在编译时检查两者是否具有相同类型的方法是:

template< typename T, typename U >
void assert_same_type( T const&, U const& )
{
     int error[ sizeof( T ) ? -1 : -2 ]; // error array of negative size, dependent on T otherwise some implementations may cause an early error message even when they shouldn't
}
template< typename T >
void assert_same_type( T&, T& ){}
void MyClass::setX(double input)
{
   assert_same_type( x, input ); // If the fallback case is instantiated then a compile time error will arise of trying to declare an array of negative size.
   x = input;
}

您可以创建一个模板函数,然后像这样重载double的参数类型:

#include <cassert>
template<class T>
bool is_double(T) { return false; }
bool is_double(double) { return true; }
int main() {
    int i = 1;
    double d = 3.14;
    assert( is_double(d) );
    assert( is_double(i) ); // fails
}

将给出一个运行时错误。只需定义一个接受双引用的函数,就可以生成编译时错误:

void is_double(double&) { }
void MyClass::setX(double input)
{
  is_double(x); // assert x is double
  x = input;
}