[英]C++17 can variadic template class define new type and variadic data member?
#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:我有一个 class
ClazN
,我:
T1
, T2
... Tn
have no relationship. T1
, T2
... Tn
没有关系。 How to write ClazzN
?如何编写
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
.您可以使用
std::tuple
,也可以用于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:您可以使用
std::tuple_element
访问类型列表:
#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 https://gcc.godbolt.org/z/dvadxrbEM
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.