Maxim Blinov
Maxim Blinov

Reputation: 946

Categorically prevent or discourage Object instantiation with particular arguments

Consider the following class:

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; }

I wish to allow users to instantiate this class only in the cases of

Point<A, B> pt;

where A and B are not equal to zero, so the specific case of

Point<0, 0> pt;

should be disallowed.

What is the best method of discouraging users from being able to create such an object, and even prevent its use? (e.g. calling member functions and the like.)

For example, is it maybe possible to make it so that, in the case of Point<0, 0>, the constructor called is private? Or perhaps calling the destructor from within the constructor in the template specialisation of said Point constructor?

Upvotes: 1

Views: 41

Answers (1)

user2249683
user2249683

Reputation:

Just place a 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;
}

Disclaimer: I do not see a use case for the template.

Upvotes: 1

Related Questions