[英]Type trait through a variable of the type
我想測試一個變量類型的屬性。 我可以,但是代碼太冗長了。
考慮一個示例,其中我定義了一個與容器中值的類型相同類型的變量:
#include <vector>
int main() {
std::vector<int> v, &rv=v;
// ‘rv’ is not a class, namespace, or enumeration
//rv::value_type i1;
// Ok
decltype(v)::value_type i2;
// decltype evaluates to ‘std::vector<int>&’, which is not a class or enumeration type
//decltype(rv)::value_type i3;
// Ok
std::remove_reference<decltype(rv)>::type::value_type i4;
}
我可以接受decltype
,但添加std::remove_reference
太多了。 有沒有什么好的方法可以縮短代碼,而無需定義輔助模板?
您可以使用以下方法之一縮短它
std::decay_t<decltype(rv)>::value_type i4 = 42;
或者
std::decay_t<decltype(*std::begin(rv))> i4 = 42;
使用一些using 聲明:
using my_value_type = decltype(v)::value_type;
using your_value_type = std::remove_reference<decltype(rv)>::type::value_type;
您的代碼將變為:
int main() {
std::vector<int> v, &rv=v;
using my_value_type = decltype(v)::value_type;
using your_value_type = std::remove_reference<decltype(rv)>::type::value_type;
my_value_type i2;
your_value_type i4;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.