我一直在使用
static_assert
以及模板类(functor)来实现一些元进程功能。例如
struct triangle { unsigned int a_, b_, c_; }
struct triangleMesh { std::vector<triangle> triangles_; }
struct point2D { double x_, y_; };
struct point2D { double x_, y_, z_; };
struct mesh2D : public triangleMesh { std::vector<point2D> points_; }
struct mesh3D : public triangleMesh { std::vector<point3D> points_; }
// Generate triangle mesh implementation...
template <class R, V>
class GenerateTrianglesImpl
{
// Enforce certain combinations of types...
std::static_assert(std::is_base_of<point3D, V>::value && std::is_base_of<mesh3D, R>::value ||
std::is_base_of<point2D, V>::value && std::is_base_of<mesh2D, R>::value,
"GenerateTrianglesImpl return (R) and value (V) must be same dimension");
public:
std::shared_ptr<R> operator()(const std::vector<V>& points)
{
if (vs.size() % 3 != 0)
std::runtime_error("GenerateTrianglesImpl points input is not a multiple of 3");
// populate the mesh and return it...
return std::shared_ptr<R>(...);
}
};
在这个例子中,我可以确保我的模板类的任何调用者都提供
R
(返回类型)和
V
(值类型)相互兼容的类型,可以阻止其他开发人员使用此模板类,但没有意义
R
和
五、
类型,即。
GenerateTrianglesImpl<mesh2D, point3D>()(some3DPoints); // static_assert triggers to prevent this instantiation...
我选择了这个,因为我觉得通过以下方式强制使用类型(或组合)会稍微优雅一些
静态断言
而不是专门化,而且我还可以(潜在地)将更大的例程重构为模板类中的私有方法,而不是用模板类的辅助/辅助函数污染父名称空间。
问题。。。
这会被归类为模板专业化吗?它没有为不同类型提供不同的实现,但它强制使用某些类型(以及某些类型的组合)?
这是一种在模板中强制使用特定类型组合的好方法,而不是强制使用这些不同的组合(如果目前使用专业化对我来说是显而易见的,那么需要更多的编码)吗?
与具有这种行为的模板类相比,使用模板函数是否有优点和/或缺点(
静态断言
与专业化相反)?