c++ - static_assert to check value in non-template class's template constructor -
so, i'm looking way cause compile-time error if value used in declaring object equal value (don't wish use c's assert
macro).
yes, know why problem occurs... compiler quite clear when he/she complained expression did not evaluate constant
.
i don't want make entire class template. there little miracle workaround i'm missing?
#include <iostream> class test { private: template<class t, class t2> using both_int = std::enable_if_t<std::is_integral<t>::value && std::is_integral<t2>::value>; private: int _a, _b; public: template<class t, class t2 = t, class = both_int<t, t2>> constexpr test(const t &a, const t2 &b = 1) : _a(a), _b(b) { static_assert(b != 0, "division zero!"); } }; int main() { test obj(1, 0); //error test obj2(0, 1); //ok std::cin.get(); }
you can this:
struct test { private: constexpr test(int a, int b) {} public: template<int b> static test construct(int a) { static_assert(b != 0, "not 0 failed"); return test(a, b); } }; int main() { test foo = test::construct<1>(1); test foo = test::construct<0>(1);//compile error }
you need static constructor, because of there no way specify parameters of template constructor, see c++ template constructor
Comments
Post a Comment