[英]how to cast one type to another while preserving value category and cv-qualifiers?
正如標題所說。 C++ 已經有std::forward
,但它不能將原始類型轉換為另一個。 我想知道是否有一個 function 將一種類型轉換為另一種類型,同時保留原始類型的值類別和 cv 限定符。
假設有這樣一個 function 叫做perfect_cast
來做魔術,下面代碼的 output
#include <iostream>
#include <type_traits>
#include <format>
template <typename To, typename From>
decltype(auto) perfect_cast(From&& s)
{
// ???
}
template <std::size_t I>
struct A
{
void f()&
{
std::cout << std::format("lvalue A{:d}", I) << std::endl;
}
void f() const&
{
std::cout << std::format("const lvalue A{:d}", I) << std::endl;
}
void f()&&
{
std::cout << std::format("rvalue A{:d}", I) << std::endl;
}
void f() const&&
{
std::cout << std::format("const rvalue A{:d}", I) << std::endl;
}
};
template <std::size_t ...Is>
struct B : A<Is>... {};
auto g1()
{
return B<0, 1, 2, 3>{};
}
const auto g2()
{
return B<0, 1, 2, 3>{};
}
int main()
{
B<0, 1, 2, 3> b;
auto& b1 = b;
perfect_cast<A<0>>(b1).f();
const auto& b2 = b1;
perfect_cast<A<1>>(b2).f();
perfect_cast<A<2>>(g1()).f();
perfect_cast<A<3>>(g2()).f();
}
應該
lvalue A0
const lvalue A1
rvalue A2
const rvalue A3
組合轉換前向的用例並不多。 可以說,大多數類型轉換都會產生純右值,對於派生到基類的類型轉換,該語言已經允許將派生類視為基類,保留值類別。
例如,OP main
會更清楚地寫成:
B<0, 1, 2, 3> b;
auto& b1 = b;
b1.A<0>::f();
const auto& b2 = b1;
b2.A<1>::f();
g1().A<2>::f();
g2().A<3>::f();
見https://godbolt.org/z/Kff9zKPha
也許知道以其他一些 object y
的方式轉發 object x
存在一個看似相關的問題是有用的。 這很有用(例如,如果x
是y
的“一部分”)。 這非常有用,它被標准化為std::forward_like
。 (由於過去一些糟糕的語言設計決策,它比應有的復雜得多。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.