0
#include <iostream>

template <typename T0, typename T1>
struct Clazz {
    void doSomething(const std::shared_ptr<T0>& p0,
            const std::shared_ptr<T1>& p1) {}
    T0 t0;
    T1 t1;
};
template <typename T0, typename T1, typename T2>
struct Clazz3 {
    void doSomething(const std::shared_ptr<T0>& p0,
            const std::shared_ptr<T1>& p1,
            const std::shared_ptr<T1>& p2) {}
    T0 t0;
    T1 t1;
    T2 t1;
};

template <typename... Ts>
struct ClazzN {
    // Q1: one part: define types in doSomething
    // Q2: two part: define data members
    // using param_type = typename (std::shared_ptr<Ts>, ...) // fold expression? can it works on type part, or only value?

    // Ts... ts; // ??? pack it by tuple ???
};

int main() {
    Clazz<int, double> c2;
    Clazz3<int, double, char> c3;

    return 0;
}

I have a class ClazN, and I:

  1. want a variadic template form, instead of limiting the class template type size.
  2. want define different data members as the template type correspodingly.
  3. the T1, T2 ... Tn have no relationship.

How to write ClazzN? It's too stupid to write a lot repeated codes.

How could I do this? Need your help, thanks a lot!!!

xishvai
  • 3
  • 2

2 Answers2

1

You can use std::tuple, also for the param_type. In case you want a tuple of shared pointers, that is:

#include <tuple>
#include <iostream>
#include <memory>

template <typename... Ts>
struct Clazz {
    using param_type = typename std::tuple<std::shared_ptr<Ts>...>; 
    std::tuple<Ts...> ts;
};

int main() {
    Clazz<int, double> c0;
}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
0

You could use std::tuple_element to access the list of types:

#include <cstdint>
#include <tuple>
#include <string>

template <typename... Ts>
struct Clazz {
    template<std::size_t I>
    using T = std::tuple_element_t<I, std::tuple<Ts...>>;
};


using Test = Clazz<int, int&, double, std::string>;
static_assert(std::is_same_v<Test::T<0>, int>, "");
static_assert(std::is_same_v<Test::T<1>, int&>, "");
static_assert(std::is_same_v<Test::T<2>, double>, "");
static_assert(std::is_same_v<Test::T<3>, std::string>, "");

https://gcc.godbolt.org/z/dvadxrbEM

Simon Kraemer
  • 5,700
  • 1
  • 19
  • 49