从类别上防止或阻止使用特定参数实例化对象
Categorically prevent or discourage Object instantiation with particular arguments
考虑以下类:
template<int A, int B>
class Point
{
int x;
int y;
public:
Point() : x(A), y(B) { std::cout << "This is allowed" << std::endl; }
};
template<> Point<0, 0>::Point() { std::cout << "This is not allowed" << std::endl; }
我希望允许用户只在的情况下实例化这个类
Point<A, B> pt;
其中A和B不等于零,因此的具体情况
Point<0, 0> pt;
应该被禁止。
阻止用户创建这样的对象,甚至阻止其使用的最佳方法是什么?(例如呼叫成员功能等。)
例如,在Point<0, 0>
的情况下,是否可以将其设置为私有构造函数?或者在所述Point构造函数的模板专业化中,从构造函数内部调用析构函数?
只需放置一个static_assert:
template<int A, int B>
class Point
{
int x;
int y;
public:
Point() : x(A), y(B)
{
static_assert( ! (A == 0 && B == 0), "This is not allowed");
}
};
int main()
{
// This is not allowed:
// Point<0, 0> p00;
Point<0, 1> p01;
Point<1, 0> p10;
return 0;
}
免责声明:我没有看到模板的用例。
相关文章:
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- Arduino C++在构造函数中用参数声明对象数组
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- C++ 类对象作为函数参数
- 如何将对象数组作为参数传递给模板
- 使用向量初始化参数化构造函数的对象数组
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 如何编写将展开以定义具有模板参数的对象的宏
- C++类对象 - 遍历基于参数的对象
- 将指针传递到成员的指针,从模板参数包到函数对象
- 如何将子类作为函数的参数传递给期望基类,然后将该对象传递到指向这些抽象类对象的指针向量中?
- 是否可以获取成员函数模板参数的拥有对象?
- C++多参数对象创建
- 在不创建参数对象的情况下解析constexpr函数
- 推断模板参数对象成员的类型
- 如何解析c++ v8中的参数对象
- 当默认参数对象被销毁时
- 为什么函数不能更改其参数对象的地址/引用值?