gpt4 book ai didi

c++ - 转发参数的可变参数列表

转载 作者:行者123 更新时间:2023-12-02 17:34:43 26 4
gpt4 key购买 nike

下面的代码都按预期编译并执行,它们有什么不同吗?

template<typename T, typename ...U>
auto time_function(T&& func, U&& ...args)
{
std::cout << "timing" << std::endl;
auto val = std::forward<T>(func)(std::forward<U...>(args...));
std::cout << "timing over" << std::endl;
return val;
}

template<typename T, typename ...U>
auto time_function(T&& func, U&& ...args)
{
std::cout << "timing" << std::endl;
auto val = std::forward<T>(func)(std::forward<U>(args)...);
std::cout << "timing over" << std::endl;
return val;
}

查看SO How would one call std::forward on all arguments in a variadic function? ,第二个似乎是推荐的,但是第一个不是做同样的事情吗?

最佳答案

它们不一样。在数量为args的情况下它们是相同的。为1或0。否则将无法编译,请考虑..

#include <iostream>
using namespace std;
template<typename T, typename ...U>
auto time_function_1(T&& func, U&& ...args)
{

std::cout<<"timing"<<std::endl;
auto val = std::forward<T>(func)(std::forward<U...>(args...));
std::cout<<"timing over"<<std::endl;
return val;
}

template<typename T, typename ...U>
auto time_function_2(T&& func, U&& ...args)
{

std::cout<<"timing"<<std::endl;
auto val = std::forward<T>(func)(std::forward<U>(args)...);
std::cout<<"timing over"<<std::endl;
return val;
}



int f (int){return 0;}

int y (int,int){return 0;}

int main() {
time_function_1(f,1);
time_function_2(f,1);

time_function_1(y,1,2); // fail
time_function_2(y,1,2);
return 0;
}

Demo

失败案例std::forward<U...>(args...)扩展到forward<int, int>(int&, int&)并且将无法编译。

std::forward<U>(args)...扩展到std::forward<int>(int&),std::forward<int>(int&)

关于c++ - 转发参数的可变参数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58652481/

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