gpt4 book ai didi

C++ std::forward 没有 T&&

转载 作者:行者123 更新时间:2023-11-28 05:09:01 25 4
gpt4 key购买 nike

template<typename...Ts>
struct Wrapper{
using result_type = void (*)(Ts...);

template<typename T, T (*P)(Ts...)>
static result_type wrap(){
return [](Ts...ts) {
P(forward<Ts>(ts)...); // The forward is required, or the code below will fail.
};
};

};

int fun(int&& i, int& j, int k) {
return 0;
}

auto wrapped = Wrapper<int&&, int&, int>::wrap<int, fun>();
int i = 2;
wrapped(1, i, 3);

有效,问题是,当传递一个无引用类型时,forward 会将其参数转换为右值,这意味着在上面的代码中第三个参数将被移动。那么如何在没有T&&的情况下转发确切的类型呢?

最佳答案

您可以在此处使用 static_cast 而不是 forward,因为您的目标是转换为 Ts... 中指定的确切类型:

// ...
P(static_cast<Ts>(ts)...);
// ...

关于C++ std::forward 没有 T&&,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43935002/

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