模板依赖构造函数参数长度 [英] template dependent constructor argument lengths
问题描述
我尝试创建一个通用但仍然有效的多维点
类。
I try to make a generic, but still efficient multi dimension Point
class.
维度
枚举
enum Dimension : std::size_t { _2D = 2, _3D = 3 };
和点
class
template <typename T, Dimension D>
class Point : public std::array<T, D>
{
public:
T& at(size_t idx) { return std::array<T,D>::at(idx); };
const T& at(size_t idx) const { return std::array<T,D>::at(idx); };
Dimension dim() const { return D; }
...
};
我想创建nices构造函数,所以我添加了(在我的类定义之外)
I would like to create nices constructors so I added (outside my class definition)
template <typename T>
Point<T,_2D>::Point(T x, T y) { at(0) = x; at(1) = y; }
template <typename T>
Point<T,_3D>::Point(T x, T y, T z) { at(0) = x; at(1) = y; at(2) = z; }
但是我不能使用thoses。编译器告诉我只注册默认(空)和复制构造函数。
But still I cannot use thoses. The compiler tells me only default (empty) and copy constructors are registered.
定义构造函数的参数列表长度取决于我的 Dimension
模板?
How do I define constructors with arguments list length being dependant on my Dimension
template ?
推荐答案
有几种方法可以实现这一点。在您的情况下,最容易使用 std :: enable_if
:
There are a few ways to accomplish this. In your case, it might be easiest to use std::enable_if
:
template <typename T, Dimension D>
class Point : public std::array<T, D>
{
public:
template <
Dimension D2=D,
typename = typename std::enable_if<D2==_2D>::type
>
Point(T x,T y);
template <
Dimension D2=D,
typename = typename std::enable_if<D2==_3D>::type
>
Point(T x,T y,T z);
T& at(size_t idx) { return std::array<T,D>::at(idx); };
const T& at(size_t idx) const { return std::array<T,D>::at(idx); };
Dimension dim() const { return D; }
...
};
另一种选择是将其分成多个类并使用专门化:
Another option would be to break this into multiple classes and use specialization:
template <typename T, Dimension D>
class PointBase : public std::array<T, D>
{
public:
T& at(size_t idx) { return std::array<T,D>::at(idx); };
const T& at(size_t idx) const { return std::array<T,D>::at(idx); };
Dimension dim() const { return D; }
...
};
template <typename T, Dimension D> class Point;
template <typename T>
class Point<T,_2D> : public PointBase<T,_2D> {
public:
Point(T x,T y);
};
template <typename T>
class Point<T,_3D> : public PointBase<T,_3D> {
public:
Point(T x,T y,T z);
};
这篇关于模板依赖构造函数参数长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!