gpt4 book ai didi

c++ - Variadic 模板不打印最后一个参数

转载 作者:太空宇宙 更新时间:2023-11-03 10:39:03 27 4
gpt4 key购买 nike

为了我的理解,我正在尝试使用可变参数模板编写一个简单的记录器。它有效,但有一个问题。

void log() {
std::cout << std::endl;
}
// variadic Template
template<class T, class... Args>
void log(T t1, Args... args) {
std::cout << t1<<" ";
log(args...);
}

int main()
{
log("Logging", 1, 2, 3.2, 4);
return 0;
}

这不是在控制台输出最后一个参数'4'。这个的输出是

记录 1 2 3.2

当我调试时,它根本没有进入“空”日志功能。事实上,它编译并给出相同的输出,但没有那个空的 log() 函数。

有人可以解释为什么会这样吗?

最佳答案

在 Visual Studio 中,使用命名空间与标准函数名称相似是否更好

log(4) 的全局命名空间调用计算为在 xtgmath.h 中定义的宏 _GENERIC_MATH1(log, _CRTDEFAULT)

enter image description here

#include <iostream> // - this indirectly includes macro _GENERIC_MATH1 from ^^^^^^^
namespace mylog{

void log() {}

// variadic Template
template<class T, class... Args>
void log(T t1, Args... args)
{
std::cout << t1 << " ";
log(args...); // calling log with parameter pack
// but the last call is log(4)
// which is calling macro _GENERIC_MATH1 in global namespace
}
}

int main()
{
mylog::log("Logging", 1, 2, 3.2, 4);
return 0;
}

有关更多信息,请查看 Some programmer dude回答。

关于c++ - Variadic 模板不打印最后一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49378231/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com