【问题标题】:Is there a way to test nontype templates using Boost Test?有没有办法使用 Boost Test 来测试非类型模板?
【发布时间】:2020-11-29 22:08:50
【问题描述】:

我正在使用 Boost Unit Test 为我的项目执行单元测试。我需要测试一些非类型模板,但似乎使用宏 BOOST_AUTO_TEST_CASE_TEMPLATE(test_case_name, formal_type_parameter_name, collection_of_types) 我只能测试类型模板。我想使用不是由{ int, float, ...} 组成的collection_of_types,而是{0,1,2, ...}

这是我想做的一个例子:

#include <boost/test/included/unit_test.hpp>
#include <boost/mpl/list.hpp>

typedef boost::mpl::list<0, 1, 2, 4, 6> test_types;

BOOST_AUTO_TEST_CASE_TEMPLATE( my_test, T, test_types )
{
  test_template<T>* test_tmpl = new test_template<T>();

  // other code
}

【问题讨论】:

    标签: c++ boost boost-test


    【解决方案1】:

    您总是可以将静态常量包装在一个类型中。对于整数类型,有 std::integral_constant 或者实际上是 Boost MPL 模拟:

    Live On Coliru

    #define BOOST_TEST_MODULE sotest
    #define BOOST_TEST_MAIN
    
    #include <boost/mpl/list.hpp>
    #include <boost/test/included/unit_test.hpp>
    
    template <int> struct test_template {};
    
    typedef boost::mpl::list<
        boost::mpl::integral_c<int, 0>,
        boost::mpl::integral_c<int, 1>,
        boost::mpl::integral_c<int, 2>,
        boost::mpl::integral_c<int, 4>,
        boost::mpl::integral_c<int, 6>
    > test_types;
    
    BOOST_AUTO_TEST_CASE_TEMPLATE(my_test, T, test_types) {
        test_template<T::value>* test_tmpl = new test_template<T::value>();
    
        // other code
        delete test_tmpl;
    }
    

    打印

    Running 5 test cases...
    
    *** No errors detected
    

    奖金提示

    为了节省打字,您可以使用可变参数模板别名:

    template <typename T, T... vv> using vlist =
        boost::mpl::list<boost::mpl::integral_c<T, vv>... >;
    

    现在您可以将列表定义为:

    Live On Coliru

    using test_types = vlist<int, 0, 1, 2, 4, 6>;
    

    【讨论】:

      猜你喜欢
      • 2017-02-10
      • 1970-01-01
      • 2020-04-28
      • 1970-01-01
      • 1970-01-01
      • 2019-08-16
      • 2019-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多