我想制作一个类模板RestrictedInteger
,该模板只能使用在编译时已知的某些值构造。这是我可以手动完成的方式:
// Wrapper
template<int... Is> using IntList = std::integer_sequence<int, Is...>;
// This is my class
template<class intList> class RestrictedInteger;
template<int I1>
class RestrictedInteger<IntList<I1>> {
const int _i;
public:
constexpr RestrictedInteger(std::integral_constant<int, I1>) : _i(I1) {}
};
//[...]
template<int I1, I2, I3>
class RestrictedInteger<IntList<I1, I2, I3>> {
const int _i;
public:
constexpr RestrictedInteger(std::integral_constant<int, I1>) : _i(I1) {}
constexpr RestrictedInteger(std::integral_constant<int, I2>) : _i(I2) {}
constexpr RestrictedInteger(std::integral_constant<int, I3>) : _i(I3) {}
};
//[...] (and so on)
自然,我想改用可变参数模板。 如果只有这样:
template<int... Is>
class RestrictedInteger<IntList<Is...>> {
int _i;
public:
constexpr RestrictedInteger(std::integral_constant<int, Is>) : _i(Is) {}... // ERROR
}
但是,由于我使用的是C ++ 17,所以我认为它会像这样工作:
template<int... Is>
class RestrictedInteger<IntList<Is...>> {
int _i;
public:
template<int I>
constexpr RestrictedInteger(std::enable_if_t<...||(I==Is), std::integral_constant<int, I>>) : _i(I) {} // syntax error: '...' (Visual Stuio 2019)
};
但显然不是。
有什么巧妙的方法可以解决这个问题吗?
答案 0 :(得分:4)
如果编译失败是一种选择(不需要编译器来查找其他重载),则可以将static_assert
放在构造函数中:
#include <type_traits>
#include <utility>
template<int... Is> using IntList = std::integer_sequence<int, Is...>;
template<class intList> class RestrictedInteger;
template<int... Is>
class RestrictedInteger<IntList<Is...>> {
private:
const int _i;
public:
template <int I>
constexpr RestrictedInteger(std::integral_constant<int, I>) : _i(I)
{
static_assert(((I == Is) || ...), "Invalid value");
}
};
int main()
{
RestrictedInteger<IntList<1, 2, 3>> i = std::integral_constant<int, 3>();
RestrictedInteger<IntList<1, 2, 3>> ii = std::integral_constant<int, 6>(); // fails
}
或使用std::enable_if
的详细解决方案:
#include <type_traits>
#include <utility>
template<int... Is> using IntList = std::integer_sequence<int, Is...>;
template<class intList> class RestrictedInteger;
template<int... Is>
class RestrictedInteger<IntList<Is...>> {
private:
const int _i;
public:
template <int I, typename std::enable_if_t<((I == Is) || ...)>* = nullptr>
constexpr RestrictedInteger(std::integral_constant<int, I>) : _i(I)
{
}
};
int main()
{
RestrictedInteger<IntList<1, 2, 3>> i = std::integral_constant<int, 3>();
RestrictedInteger<IntList<1, 2, 3>> ii = std::integral_constant<int, 6>(); // fails
}