gpt4 book ai didi

c++ - 函数模板的这两个定义有什么区别?

转载 作者:行者123 更新时间:2023-11-30 01:13:36 25 4
gpt4 key购买 nike

template <typename Func, typename... Args>
static void WraperFunc(Func func, Args &&... args) {
SomeFunc(func, args...);
}

对比

template <typename Func, typename... Args>
static void WraperFunc(Func func, Args ... args) {
SomeFunc(func, args...);
}

哪个更好更推荐?或者是否有比两者都更好的替代方案?

最佳答案

Args && 将通过引用接受左值和右值,并使它们能够在保持其原始状态的情况下被转发 value category .我更喜欢那个版本(并使用 std::forward)。

template <typename Func, typename... Args>
static void WraperFunc(Func func, Args &&... args) {
SomeFunc(func, std::forward<Args>(args)...);
// ^^^^^^^^^^^^ Use of forward
}

注意 std::forward 的惯用用法,它不包括 Args&&&&

有很多关于 std::forward 和引用折叠的机制和使用的文章,hereScott Meyers classic关于“转发(或通用)引用”。

关于c++ - 函数模板的这两个定义有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31795322/

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