gpt4 book ai didi

c++ - 完善的转发功能推导出冲突错误

转载 作者:行者123 更新时间:2023-11-30 03:24:11 44 4
gpt4 key购买 nike

我正在测试完美转发,我不明白为什么 TEST_EQ(string("olleH"), s) 编译失败,但是 string("olleH") == s编译通过。如何在此处修复我的 TEST_EQ 函数?

template<typename S>
static bool TEST_EQ(S&& a, S&& b)
{
return forward<S>(a) == forward<S>(b);
}


int main()
{
string s= "Hello";

cout << TEST_EQ(string("olleH"), s) << endl;
cout << (string("olleH") == s);

}

最佳答案

根据forwarding reference的推算规则,当您尝试将 TEST_EQ 调用为 TEST_EQ(string("olleH"), s) 时,对于参数 string("olleH") ,它是一个右值,那么 S 将被推断为 std::string;对于参数 s,它是一个左值,那么 S 将被推断为 std::string&。推导结果冲突,调用失败。

您可以添加另一个模板参数来避免这种推导冲突,例如

template<typename S, typename T>
static bool TEST_EQ(S&& a, T&& b)
{
// if you need to check that S and T should be the same type
static_assert(is_same_v<remove_cvref_t<S>, remove_cvref_t<T>>, "S and T must be the same type.");

return forward<S>(a) == forward<T>(b);
}

LIVE

关于c++ - 完善的转发功能推导出冲突错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49868433/

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