I am testing perfect forwarding, and I dont understand why TEST_EQ(string("olleH"), s)
compile failed, but string("olleH") == s
compile pass. How do I fix my TEST_EQ
function here?
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);
}
According to the deduction rule of forwarding reference, when you try to call TEST_EQ
as TEST_EQ(string("olleH"), s)
, for the argument string("olleH")
, which is an rvalue, then S
will be deduced as std::string
; for the argument s
, which is an lvalue, then S
will be deduced as std::string&
. The deduction result is conflicting then the calling fails.
You can add another template parameter to avoid such deduction conflicting, e.g.
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);
}