不完整的类型 std::tuple_size即使<T> T 是完整的?



在下面的代码中,我尝试获取从std::tuple派生的自定义类型的元组大小。但是编译器抱怨std::tuple_size是不完整的…我真的不能理解,因为struct foo在这一点上已经很好地定义了。type_descriptor<foo>的情况自然也是如此。这个错误从何而来?

演示
#include <utility>
#include <tuple>
#include <cstdio>

struct foo
{
int a_;
int b_;
};
template <typename T>
struct type_descriptor
{};
template<>
struct type_descriptor<foo>
: std::tuple<int, bool>
{
};
int main(){
printf("Size of tuple = %zun", std::tuple_size_v<type_descriptor<foo>>);
}

这会产生以下错误:

<source>:89:27:   required from here
/opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/bits/utility.h:75:61: error: incomplete type 'std::tuple_size<type_declarator<foo> >' used in nested name specifier
75 |     inline constexpr size_t tuple_size_v = tuple_size<_Tp>::value;
|   

继承并不意味着等价。您的类型type_descriptor<foo>继承自std::tuple<int, bool>,但它不是相同的类型。因此模板参数匹配将找不到它。如果你想让它工作,你需要,例如,在type_descriptor<foo>里面有一个类型正好是std::tuple<int, bool>:

template<>
struct type_descriptor<foo>
{
using type = std::tuple<int, bool>;
};
int main(){
printf("Size of tuple = %zun", std::tuple_size_v<type_descriptor<foo>::type>);
}

最新更新