能否为GTest类型参数化测试宏传入类型列表?
实现方法:用Boost.MP11动态生成GTest类型参数化测试的类型列表
完全可以实现,核心是通过模板元编程将Boost.MP11的类型列表转换为GTest ::testing::Types<>所需的参数包。以下是具体步骤和示例:
1. 定义类型转换辅助模板
先写一个简单的模板特化,把MP11的mp_list(或其他MP11类型列表)展开为GTest的Types模板参数:
#include <gtest/gtest.h> #include <boost/mp11/mp_list.hpp> // 辅助模板:将MP11类型列表转换为GTest Types template <typename MpList> struct MpListToGTestTypes; // 特化处理mp_list<Ts...> template <typename... Ts> struct MpListToGTestTypes<boost::mp11::mp_list<Ts...>> { using type = ::testing::Types<Ts...>; }; // 简化别名 template <typename MpList> using MpListToGTestTypes_t = typename MpListToGTestTypes<MpList>::type;
2. 用MP11动态构建类型列表
利用MP11的元函数(如mp_list、mp_filter、mp_transform、mp_append等)生成你需要的类型集合,无需硬编码:
#include <boost/mp11/mp_filter.hpp> #include <boost/mp11/mp_transform.hpp> #include <string> #include <vector> // 自定义类型 struct MyTypeA {}; struct MyTypeB {}; struct MyTypeC {}; // 示例1:直接构建基础类型列表 using BasicTypes = boost::mp11::mp_list<int, float, double, std::string>; // 示例2:过滤出满足条件的类型(比如仅自定义类型) template <typename T> struct IsCustomType : std::false_type {}; template <> struct IsCustomType<MyTypeA> : std::true_type {}; template <> struct IsCustomType<MyTypeB> : std::true_type {}; using CustomTypes = boost::mp11::mp_filter<IsCustomType, boost::mp11::mp_list<MyTypeA, MyTypeB, MyTypeC, int>>; // 示例3:转换类型(比如给基础类型套上vector) using VectorTypes = boost::mp11::mp_transform<std::vector, BasicTypes>;
3. 在GTest类型参数化测试中使用
将转换后的类型列表传入测试类的TypeParam:
// 定义类型参数化测试类 template <typename T> class DynamicTypeTest : public ::testing::Test {}; // 使用MP11生成的自定义类型列表 TYPED_TEST_SUITE(DynamicTypeTest, MpListToGTestTypes_t<CustomTypes>); // 编写测试用例 TYPED_TEST(DynamicTypeTest, TypeProperties) { // 验证当前TypeParam是自定义类型 EXPECT_TRUE((std::is_same_v<TypeParam, MyTypeA> || std::is_same_v<TypeParam, MyTypeB>)); } // 切换使用容器类型列表 TYPED_TEST_SUITE(DynamicTypeTest, MpListToGTestTypes_t<VectorTypes>); TYPED_TEST(DynamicTypeTest, VectorDefaultSize) { TypeParam vec; EXPECT_EQ(vec.size(), 0); }
关键说明
- 兼容性:确保你的GTest版本支持可变参数模板(GTest 1.8.0及以上基本都支持),Boost.MP11建议使用1.70.0及以上版本。
- 扩展性:MP11的所有元函数都可用来动态生成类型列表,比如
mp_append合并多个列表、mp_repeat重复类型、mp_sort排序类型等,完全替代硬编码的::testing::Types<>。 - 编译期处理:所有类型列表的构建和转换都在编译期完成,不会影响运行时性能。
内容的提问来源于stack exchange,提问作者neuron mac
相关产品推荐
相关产品推荐

