C++模板类实现队列时vector的assign方法编译报错如何解决?
错误原因
C++模板实例化过程中,普通if语句的所有分支都会被编译检查,不会因为分支条件不成立就跳过非激活分支的语法校验。当你实例化queueWithArray<int>时,queueArray是std::vector<int>类型,此时if(is_same<T,string>::value)分支里的queueArray.assign(n,"")代码仍然会被编译,而int类型的vector无法接收字符串字面量作为填充值,因此触发函数匹配错误。
修复方案
方案1:极简通用方案(兼容所有C++版本,无需类型判断)
你要的填充值刚好是对应类型的默认构造结果:std::string默认构造是空串,int默认构造是0,完全不需要做类型分支判断,直接替换构造函数里的逻辑即可:
#include <type_traits> // 保留用于is_same判断输出类型 queueWithArray(int n) { numberOfElements = 0; head = -1; tail = -1; size = n; if(is_same<T,std::string>::value) { std::cout << "data type is string" << std::endl; } // 直接用T的默认实例填充,兼容所有可默认构造的类型 queueArray.assign(n, T()); }
方案2:C++17及以上版本可用if constexpr
如果确实需要做类型分支的差异化逻辑,用if constexpr替代普通if,编译期就会裁剪掉非激活分支,不会参与编译:
#include <type_traits> queueWithArray(int n) { numberOfElements = 0; head = -1; tail = -1; size = n; if constexpr (is_same<T,std::string>::value) { std::cout << "data type is string" << std::endl; queueArray.assign(n,""); } else { queueArray.assign(n,0); } }
额外注意事项
你的main函数中存在笔误,int队列的循环末尾调用的是obj.printQueue(),应该改为obj_int.printQueue(),否则会触发变量作用域错误。
内容的提问来源于stack exchange,提问作者rajeshkb
相关产品推荐
相关产品推荐

