你能用assert来测试C++中的类型定义吗?

Elp*_*rto 3 c++ debugging assert casting

我可以使用assert来强制执行类型定义.假设有一个变量,double d你如何assert断言d是双精度?如果assert不适用(我打赌不是),还有其他选择吗?我特别希望测试调试过程中隐含的类型转换,而从功能中受益assert#define NDEBUG.

PS显然我想将它用于任何类型定义,这里只使用double作为示例.该解决方案应该是跨平台兼容的并且与C++ 03兼容.

我想将错误检查添加到我的类设置器中.例如,假设有一个类MyClass,它带有一个私有成员变量x:

void MyClass::setX(double input)
{
   // assert x is double
   x = input;
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*err 7

它实际上是一个编译时检查,所以你应该使用静态断言.

这是一个使用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>();
}
Run Code Online (Sandbox Code Playgroud)

无论如何,我认为你的意思是模板.

  • 这是`BOOST_STATIC_ASSERT`,它可能需要双重parens,因为参数有一个逗号. (2认同)

Elp*_*rto 5

您可以使用类中==定义的运算符来测试特定的类型定义。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
}
Run Code Online (Sandbox Code Playgroud)

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

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)