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

时间:2017-06-15 11:34:42

标签: 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() {
}

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:4)

petersohn's answer启发

你也可以这样做:

template <typename U, U... Ts>
struct PgmArray final {
    using T = std::remove_const_t<std::remove_reference_t<U>>;

    static constexpr uint8_t size = sizeof... (Ts);
    static constexpr T data[] {Ts...};
};

constexpr auto x3 = PgmArray<const A&, a1, a2>{}; // ok
constexpr auto x4 = PgmArray<int, 1, 2>{}; // ok

答案 2 :(得分:2)

让我们反转@bolov的做法并将操作放入参数包的类型中:

// separate alias template not strictly necessary, but easier for readability
template<class T>
using maybe_cref = std::conditional_t<std::is_integral_v<T>, T, const T&>;

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