结合两个几乎相同的类模板

wim*_*aan 2 c++ variadic-templates c++17

下面是两个大多数相同的模板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() {
}
Run Code Online (Sandbox Code Playgroud)

pet*_*ohn 5

它不是更少的代码,但如果你经常改变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
Run Code Online (Sandbox Code Playgroud)