#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:
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!!!
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;
}
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>, "");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.