c++ - 根据参数包值定义模板

此类中的方法使用索引序列,其中包含覆盖整个 data 元组的索引序列(参数包中传递的每个参数的索引)。根据我看到的其他答案,我目前正在对我的方法进行模板化:

#include <tuple>
#include <memory>
#include <vector>

using std::tuple;

template <typename... Args>
class Foo
{
    protected:
        tuple<std::shared_ptr<std::vector<Args>>...> data;

    private:

        template<size_t...Is>
        void _clear_(std::index_sequence<Is...>) {
            (std::get<Is>(data)->clear(), ...);
        };

    public:

        void clear()
        { _clear_(std::index_sequence_for<Args...>()); };
};

不过,这看起来很困惑。我想知道是否有一种方法可以在类级别范围内定义 Is(或者,更一般地说,是否有更好的方法来做到这一点)。

最佳答案

对于 C++17,您可以简单地使用 std::apply :

void clear()
{
    std::apply([](auto&... vs){ (vs.clear(), ...); }, data);
}

I was wondering if there's a way that I could define Is at a class-level scope

有额外的层:

template <typename Seq, typename...> class FooImpl;

template <std::size_t... Is, typename... Ts>
class FooImpl<std::index_sequence<Is...>, Ts...>
{
protected:
    std::tuple<std::shared_ptr<std::vector<Ts>>...> data;

public:
    void clear() { (std::get<Is>(data).clear(), ...); };
};

template <typename... Ts>
using Foo = FooImpl<std::make_index_sequence<sizeof...(Ts)>, Ts...>;

https://stackoverflow.com/questions/68184805/

相关文章:

c++ - STL 中的 find() 与 binary_search()

javascript - 嵌入 : DiscordAPIError: Cannot send an

cuda - Nvidia GPU 可以启动多少个线程?

python - 从列表中删除字典

windows - 程序计数器、栅栏和处理器重新排序

mysql - SQL 查询问题 (MySQL)

rust - 为什么 [u8] 没有实现 Clone?

r - 您如何使用 Pearson 相关性来选择 `R` 中的特征?

rust - 仅当处于 Release模式时,我如何在没有窗口的情况下运行 Rust 程序

sql-server - 通过 docker 创建的默认 SQL Server 凭据是什么?