欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 美景 > C++ 不定参数模版

C++ 不定参数模版

2025/5/9 17:25:35 来源:https://blog.csdn.net/auccy/article/details/139604390  浏览:    关键词:C++ 不定参数模版

使用不定参数模版遇到一个小问题,做个记录

测试代码如下:

template<typename T, typename ...Args>
void pushToVectorIfParamIsStr(std::vector<std::string>& vec, T &&value,Args&&... args) {const bool is = std::is_same_v<T, std::string> ||std::is_same_v<T, const char*>;if (is) {vec.push_back(std::forward<T>(value));}const int count = sizeof...(args);if constexpr (count > 0) {pushToVectorIfParamIsStr(vec, std::forward<Args>(args)...);}
}template<typename ...Args>
void testFunc(const std::string& buff, Args& ... args)
{std::vector<std::string> vec;if constexpr (sizeof...(args) > 0) {pushToVectorIfParamIsStr(vec, std::forward<Args>(args)...);}for (auto &a:vec){std::cout << a << std::endl;}
}int main() 
{auto a = "a";const char* b = "b";testFunc("", a, b, "c", std::string("d"));return 0;
}

预期vec中推入的字符串是a,b,c,d,实际只推入了a,b,d,字符串"c"并没有被推入vec,什么原因呢?

这是因为字符串字面量(如 "a")在大多数上下文中都被视为字符数组,但是它们的实际处理方式会根据它们如何被使用而有所不同。

对于

auto a = "a";

定义auto类型的变量并初始化为一个字符串字面量时,编译器会进行类型推导。由于 "a" 是一个字符串字面量,它在内存中是作为一个常量字符数组存在的,但在这里并没有引用整个数组,而是将整个字符串字面量赋值给一个变量。将字符串字面量赋值给一个非引用类型的变量时,它通常会“衰变”(decay)为一个指向其第一个字符的指针,即 char const*

因此,此处的变量a被推导为 char const* 类型。

对于参数列表的中"c"

testFunc("", a, b, "c", std::string("d"));

pushToVectorIfParamIsStr函数中的T &&value参数 ,为右值引用,接收到参数"c"时,其类型依然为char const [],因此无法通过下面代码的检测

const bool is = std::is_same_v<T, std::string> ||std::is_same_v<T, const char*>;

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词