C++ 编写混合类型与非类型模板函数 适配多bool实参不修改Test类
混合类型与非类型模板参数的函数正确定义方法
最小可复现代码
#include <unordered_map> #include <string> template<class T, bool did_work> class Test { Test(T input) : field(input), success(did_work) {} T field; bool success; }; template<typename A> void func(std::unordered_map<std::string, Test<A, bool>> input1, A input2) {} int main() {}
编译输出
$ g++ -std=c++17 -ggdb -g3 -Wall test.cpp && ./a.out test.cpp:12:51: error: type/value mismatch at argument 2 in template parameter list for ‘template<class T, bool did_work> class Test’ 12 | void func(std::unordered_map<std::string, Test<A, bool>> input1, A input2) {} | ^~~~ test.cpp:12:51: note: expected a constant of type ‘bool’, got ‘bool’ test.cpp:12:55: error: template argument 2 is invalid 12 | void func(std::unordered_map<std::string, Test<A, bool>> input1, A input2) {} | ^~ test.cpp:12:55: error: template argument 5 is invalid
问题核心
- 已定义的
Test类第二个模板参数是非类型模板参数,要求传入编译期可确定的bool常量,不能传入bool类型本身 - 原
func签名错误将bool类型作为Test的第二个模板实参,违反非类型模板参数的传参规则,直接触发编译报错 - 实际需求约束:不修改现有
Test类的定义,让func能同时接收两种类型的入参:std::unordered_map<std::string, Test<A, true>>类型的参数std::unordered_map<std::string, Test<A, false>>类型的参数
可行实现方案
只需要修正func的模板参数列表,增加对应的非类型bool形参即可,不需要改动Test类的定义:
- 修正后的函数正确签名
template<typename A, bool did_work> void func(std::unordered_map<std::string, Test<A, did_work>> input1, A input2) {} - 方案特性说明
- 模板参数列表同时包含类型参数
A、非类型bool参数did_work,完全匹配Test类的模板参数构成 - 调用
func时,编译器会根据传入的unordered_map的实际值类型,自动推导出A的具体类型和did_work的编译期取值,不需要手动显式传递模板参数 - 完美兼容两种
Test<A, true>/Test<A, false>的入参场景
- 模板参数列表同时包含类型参数
- 完整可编译的参考代码
#include <unordered_map> #include <string> template<class T, bool did_work> class Test { public: Test(T input) : field(input), success(did_work) {} T field; bool success; }; // 修正后的func定义 template<typename A, bool did_work> void func(std::unordered_map<std::string, Test<A, did_work>> input1, A input2) {} int main() { std::unordered_map<std::string, Test<int, true>> map_true; std::unordered_map<std::string, Test<int, false>> map_false; // 编译器自动推导模板参数,无编译错误 func(map_true, 1); func(map_false, 2); return 0; }
内容的提问来源于stack exchange,提问作者ajoseps
相关产品推荐
相关产品推荐

