1

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?

Maxim Blinov
  • 886
  • 9
  • 33
  • 1
    Why can't you check the arguments in the body of the constructor? Throw an exception if both are zero. – Anon Mail Nov 24 '15 at 18:52
  • http://stackoverflow.com/questions/26633239/c-templates-conditionally-enabled-member-function provides some ways of doing this. – Ethan Fine Nov 24 '15 at 18:54

1 Answers1

1

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.

  • This was just a shortened example of a class that did need the templates (I think), I left them in just in case they would be relevant. – Maxim Blinov Nov 24 '15 at 19:01