我正在嘗試撰寫遍歷std::tuple元素的通用函式。在這樣做時,我需要提取正在處理的給定元組元素的元素型別。但是,我遇到了一個關于提取的型別和元組元素的實際型別之間的型別相等性的問題。下面的代碼通過將static_asserts添加到提取的型別來說明問題,這(據我所知)在兩種情況下都應該是真的:
#include <tuple>
#include <type_traits>
using TestTuple = std::tuple<int>;
template <std::size_t I = 0, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type
foo(std::tuple<Tp...> &) {}
template <std::size_t I = 0, typename... Tp>
inline typename std::enable_if <
I<sizeof...(Tp), void>::type foo(std::tuple<Tp...> &output) {
// Using tuple element
using ValueType = std::tuple_element<I, std::tuple<Tp...>>;
static_assert(std::is_same<ValueType, int>::value, "Should be true");
using ValueType2 = std::remove_reference<decltype(std::get<I>(output))>;
static_assert(std::is_same<ValueType2, int>::value, "Should be true");
}
void bar() {
TestTuple t;
foo(t);
}
嘗試通過Compiler Explorer 編譯,static_assert在 GCC 11.2 和 clang-13 上都失敗;叮當輸出是:
<source>:16:5: error: static_assert failed due to requirement 'std::is_same<std::tuple_element<0, std::tuple<int>>, int>::value' "Should be true"
static_assert(std::is_same<ValueType, int>::value, "Should be true");
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:24:5: note: in instantiation of function template specialization 'foo<0UL, int>' requested here
foo(t);
^
<source>:19:5: error: static_assert failed due to requirement 'std::is_same<std::remove_reference<int &>, int>::value' "Should be true"
static_assert(std::is_same<ValueType2, int>::value, "Should be true");
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2 errors generated.
Compiler returned: 1
uj5u.com熱心網友回復:
您沒有正確獲取元組元素的型別。他們應該是
using ValueType = typename std::tuple_element<I, std::tuple<Tp...>>::type;
// ^^^^^^^^ ^^^^^^
static_assert(std::is_same<ValueType, int>::value, "Should be true");
using ValueType2 = typename std::remove_reference<decltype(std::get<I>(output))>::type;
// ^^^^^^^^ ^^^^^^
static_assert(std::is_same<ValueType2, int>::value, "Should be true");
或 (C 14 起)
using ValueType = std::tuple_element_t<I, std::tuple<Tp...>>;
// ^^
static_assert(std::is_same<ValueType, int>::value, "Should be true");
using ValueType2 = std::remove_reference_t<decltype(std::get<I>(output))>;
// ^^
static_assert(std::is_same<ValueType2, int>::value, "Should be true");
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/326459.html
