gpt4 book ai didi

c++ - 合并两个几乎相同的类模板

转载 作者:太空狗 更新时间:2023-10-29 23:35:11 30 4
gpt4 key购买 nike

下面是两个基本相同的模板 PgmArrayPgmArrayF。第一个适用于 lvalue-ref 模板参数,第二个适用于整数参数。我喜欢将这两者合而为一:

#include <stdint.h>
#include <type_traits>
#include <array>
#include <iostream>

template<typename T, const T&... Ts>
struct PgmArray final {
static constexpr uint8_t size = sizeof... (Ts);
static constexpr T data[] {Ts...};
};

template<typename T, T... Ts>
struct PgmArrayF final {
static constexpr uint8_t size = sizeof... (Ts);
static constexpr T data[] {Ts...};
};

struct A{
uint8_t m = 0;
};

constexpr A a1{1};
constexpr A a2{2};

constexpr auto x1 = PgmArray<A, a1, a2>{}; // ok
constexpr auto x2 = PgmArrayF<int, 1, 2>{}; // ok

//constexpr auto x3 = PgmArrayF<A, a1, a2>{}; // nok
//constexpr auto x4 = PgmArray<int, 1, 2>{}; // nok

int main() {
}

最佳答案

如果您经常更改 PgmArray,它不仅代码更少,而且更易于维护。

template<typename T, T... Ts>
struct PgmArray final {
static constexpr uint8_t size = sizeof... (Ts);
static constexpr std::decay_t<T> data[] {Ts...};
};

template<typename T>
struct MakePgmArray {
using TemplateArgument = typename std::conditional_t<
std::is_integral_v<T>, T, const T&>;
template<TemplateArgument... Ts>
using type = PgmArray<TemplateArgument, Ts...>;
};

...

constexpr auto x1 = MakePgmArray<A>::type<a1, a2>{}; // ok
constexpr auto x2 = MakePgmArray<int>::type<1, 2>{}; // ok

关于c++ - 合并两个几乎相同的类模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44566469/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com