[英]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;
}
我有一個 class ClazN
,我:
T1
, T2
... Tn
沒有關系。 如何編寫ClazzN
? 寫很多重復的代碼太愚蠢了。
我怎么能這樣做? 需要您的幫助,非常感謝!!!
您可以使用std::tuple
,也可以用於param_type
。 如果你想要一個共享指針的元組,那就是:
#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;
}
您可以使用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>, "");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.