gpt4 book ai didi

c++ - 表示 C++ 类模板中的空类型

转载 作者:行者123 更新时间:2023-12-01 14:42:31 24 4
gpt4 key购买 nike

考虑以下编译时“vector ”的示例。

#include <iostream>

template <int n, int...ns>
struct static_vector {
static constexpr int value = n;
static_vector<ns...> rest;
};

template <int n>
struct static_vector<n> {
static constexpr int value = n;
void* rest;
};

template <int n, class sv>
constexpr int access_nth() {
static_assert(n >= 0, "vector size out of bound");
if constexpr(n == 0) {
return sv::value;
} else {
static_assert(!std::is_same_v<decltype(sv::rest), void *>, "vector size out of bound");
return access_nth<n-1, decltype(sv::rest)>();
}
}

int main()
{
constexpr auto a = static_vector<12, 23, 34, 45>();
constexpr int nth = access_nth<5, decltype(a)>();
std::cout << nth << std::endl;
}

我对我们现在能做的大部分感到满意​​:定义一个 vector ,然后从中取出第 n 个元素。我发现不满意的一件事是:我必须使用 void *作为基本情况下的虚拟对象(其中 vector 仅包含一个元素且没有尾部...)
我试图拥有这样的专业:
template <>
struct static_vector<> {
}
来表示空 vector 。但似乎编译器总是拒绝这个定义并出现以下错误:
<source>:16:8: error: too few template arguments for class template 'static_vector'

struct static_vector<> {

^
我应该在这里做什么才能有一个空 vector ?
非常感谢。

最佳答案

但是为什么要递归呢?
你标记了 C++17,所以你可以使用模板折叠,所以......如下呢?

#include <iostream>

template <int ... Is>
struct static_vector
{
template <std::size_t N>
int get () const
{
static_assert( N < sizeof...(Is), "index out of bound" );

std::size_t i{};
int ret;

( ... , (N == i++ ? ret = Is : 0) );

return ret;
}
};


int main()
{
constexpr auto a = static_vector<12, 23, 34, 45>();

std::cout << a.get<3u>() << std::endl;
}

关于c++ - 表示 C++ 类模板中的空类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62721992/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com