纯粹从技术方面来看,您可以(1)将具有静态存储持续时间的数组的地址constexpr
作为非类型模板参数传递:
#include <array>
template<const auto& arr>
struct gf {
gf& operator+=(const gf& /* rhs */) {
// ...
return *this;
}
};
template<const auto& arr>
auto operator+(gf<arr> lhs, const gf<arr>& rhs) {
lhs += rhs;
return lhs;
}
int main() {
// As we want to use the address of the constexpr std::array
// at compile time, it needs to have static storage duration.
static constexpr std::array<bool, 3U> p1{{0, 0, 1}};
static constexpr std::array<bool, 3U> p2{{0, 1, 1}};
gf<p1> a;
gf<p1> b;
gf<p2> c;
auto out1 = a + b; // OK.
//auto out2 = a + c; // Error: incompatible types.
}
这样gf
具有唯一数组对象的类模板的每个实例化都将成为唯一类型(/specialization)。
这依赖于 C++17auto
作为模板参数;对于类似的 C++11 方法:
#include <array>
template<std::size_t M, const std::array<bool, M>& arr>
struct gf {
gf& operator+=(const gf& /* rhs */) {
// ...
return *this;
}
};
template<std::size_t M, const std::array<bool, M>& arr>
gf<M, arr> operator+(gf<M, arr> lhs, const gf<M, arr>& rhs) {
lhs += rhs;
return lhs;
}
int main() {
// As we want to use the address of the constexpr std::array
// at compile time, it needs to have static storage duration.
static constexpr std::array<bool, 3U> p1{{0, 0, 1}};
static constexpr std::array<bool, 3U> p2{{0, 1, 1}};
gf<3U, p1> a;
gf<3U, p1> b;
gf<3U, p2> c;
auto out1 = a + b; // OK.
//auto out2 = a + c; // Error: incompatible types.
}
(1)无论如何,这个答案都没有试图将其作为任何一种好的方法来解决 OP 的 XY 式问题。