![](/img/trans.png)
[英]Can I reuse an rvalue reference parameter to return an rvalue reference?
[英]Can I determine the type of an rvalue reference?
我有一個序列化 function,它根據類型執行不同的操作。 我希望能夠同時使用f(x)
和f(5)
來調用它,但是f(5)
失敗並出現錯誤No matching function for call to 'f', Candidate function [with T = int] not viable: expects an l-value for 1st argument.
如果我將f(T& t)
更改為f(T&& t)
,則f(x)
不是算術。 我怎樣才能將f(x)
和f(5)
都識別為算術運算,並且對於任何類型(例如下面的字符串類型)也是如此? 我不想強制輸入為 const,因為我想以其他方式更改它。
template<typename T>
void f(T& t)
{
if constexpr (std::is_arithmetic_v<T>)
{
// do stuff
}
else if constexpr (std::is_same_v<T, std::string>)
{
// do other stuff
}
else
{
//alter non-const input
}
}
int main()
{
int x;
f(x);
f(5);
return 0;
}
您可以使用轉發引用T&&
來根據傳入的內容通過左值或右值引用獲取參數。
在左值的情況下, T = int&
,所以我們需要使用std::decay_t
從類型中刪除引用。
當我們傳遞一個右值時, T = int
並且 decay 什么都不做。
#include <type_traits>
#include <string>
#include <iostream>
template<typename T>
void f(T&& t)
{
using T_Type = std::decay_t<T>; // remove const/reference from the type
if constexpr (std::is_arithmetic_v<T_Type>)
{
// do stuff
}
else if constexpr (std::is_same_v<T_Type, std::string>)
{
// do other stuff
}
else
{
//alter non-const input
}
}
int main()
{
int x;
f(x);
f(5);
return 0;
}
請注意, std::decay
執行
將左值到右值、數組到指針和函數到指針的隱式轉換應用於類型 T
如果不需要任何這些情況,您可以結合使用std::remove_reference
和std::remove_const
,或者在 c++20 的情況下我們可以使用std::remove_cvref
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.