0

I would like to disallow the class templates for all the types except types class is specialized for with using static assert. Please the check the code below:

template <typename Type>
class foo {
  static_assert(false, "Wrong Type");
};

template <>
class foo<int> {
};

int main()
{
  foo<int> fi;    // should compile
  foo<double> fd; // should not compile

  return 0;
}

But it is not working. After some research I found a question answering my question: Enforce template type through static_assert

I have update the code according the question:

template <typename Type>
class foo {
  static_assert(sizeof(Type) == -1, "Wrong Type!");
};

template <>
class foo<int> {
};


int main()
{
  foo<int> fi;    // should compile
  foo<double> fd; // should not compile

  return 0;
}

My question is why the second version is OK and why not the second one?

mustafagonul
  • 1,139
  • 1
  • 15
  • 32

1 Answers1

0

So much easier:

template <typename Type>
class foo; // just don't provide an implementation...

template <>
class foo<int> { };
Aconcagua
  • 24,880
  • 4
  • 34
  • 59
  • 1
    With this way I cannot provide a message to the clients of the code. Would like to provide message code. Besides I do not search for a solution, I am seeking for a reason why I need the second version but not the first version? – mustafagonul Jul 24 '18 at 17:38
  • @mustafagonul This is a well-known pattern any half-way experienced C++ programmer should be aware of. There is no need for further overly verbose explanations... About the why: See answer to (possible) duplicate. – Aconcagua Jul 24 '18 at 17:44
  • @mustafagonul You might like the positive counter example as well: `template class C { static_assert(std::is_same::value, "wrong type"); };`, where you now would implement your int-template directly. Back to your negative example: `template class C { static_assert(!std::is_same::value, "wrong type"); };` - here, code itself shows as well what you want to achieve... – Aconcagua Jul 24 '18 at 17:51
  • By the way, you cannot prevent the user providing his/her own specialisations anyway. Sure, a different matter, but you might want to keep in mind. – Aconcagua Jul 24 '18 at 17:57