模板元编程 w/Type 特点:为什么第一个代码可以编译而第二个不能?
Template Metaprogramming w/Type Traits: Why does the first code compile and the second doesn't?
我有两组代码,第一组的编译和行为符合预期,但[似乎] 不必要地冗长:
template<point_type type, typename T>
struct point2d_base {
std::enable_if_t<std::is_arithmetic_v<T>, T> x, y;
template<point_type t2 = type>
point2d_base(std::enable_if_t<t2 == point_type::generic, T> x = 0, T y = 0) :
x(x), y(y) {}
template<point_type t2 = type>
explicit point2d_base(std::enable_if_t<t2 != point_type::generic, T> x = 0, T y = 0) :
x(x), y(y) {}
/*Some unrelated code*/
};
这是我更愿意编写的代码,但如果我这样做,我会遇到很多很多编译错误:
template<point_type type, typename T>
struct point2d_base {
std::enable_if_t<std::is_arithmetic_v<T>, T> x, y;
point2d_base(std::enable_if_t<type == point_type::generic, T> x = 0, T y = 0) :
x(x), y(y) {}
explicit point2d_base(std::enable_if_t<type != point_type::generic, T> x = 0, T y = 0) :
x(x), y(y) {}
/*Some unrelated code*/
};
为了便于参考,point_type
是一个包含三个值的 "Enum Class":generic
、corner
、center
。
我的问题是:为什么第一个代码可以编译,而第二个不能?
您不能依赖模板 class 参数来使用 std::enable_if
。
如果要将 std::enable_if
与函数一起使用,则必须将该函数设为模板函数。
这是因为当你 class 模板被实例化时,那个 class 的所有成员函数也被实例化。您需要一个模板成员函数来有条件地启用或不启用该功能。
(这是我的猜测,我认为是正确的)
我有两组代码,第一组的编译和行为符合预期,但[似乎] 不必要地冗长:
template<point_type type, typename T>
struct point2d_base {
std::enable_if_t<std::is_arithmetic_v<T>, T> x, y;
template<point_type t2 = type>
point2d_base(std::enable_if_t<t2 == point_type::generic, T> x = 0, T y = 0) :
x(x), y(y) {}
template<point_type t2 = type>
explicit point2d_base(std::enable_if_t<t2 != point_type::generic, T> x = 0, T y = 0) :
x(x), y(y) {}
/*Some unrelated code*/
};
这是我更愿意编写的代码,但如果我这样做,我会遇到很多很多编译错误:
template<point_type type, typename T>
struct point2d_base {
std::enable_if_t<std::is_arithmetic_v<T>, T> x, y;
point2d_base(std::enable_if_t<type == point_type::generic, T> x = 0, T y = 0) :
x(x), y(y) {}
explicit point2d_base(std::enable_if_t<type != point_type::generic, T> x = 0, T y = 0) :
x(x), y(y) {}
/*Some unrelated code*/
};
为了便于参考,point_type
是一个包含三个值的 "Enum Class":generic
、corner
、center
。
我的问题是:为什么第一个代码可以编译,而第二个不能?
您不能依赖模板 class 参数来使用 std::enable_if
。
如果要将 std::enable_if
与函数一起使用,则必须将该函数设为模板函数。
这是因为当你 class 模板被实例化时,那个 class 的所有成员函数也被实例化。您需要一个模板成员函数来有条件地启用或不启用该功能。
(这是我的猜测,我认为是正确的)