0

I am creating a template class in C++ for numeric operations and I want to restrict it to only numbers or similar numeric types. My question is that is there any way in C++ to restrict a template class to a specific domain as in java its simply:

public class num<N extends Number>{}

answers will be appreciated

7
  • From my knowledge there isn't. – imnota4 Oct 12 '16 at 16:30
  • This is called F-bound Polymorphism, and in C++ the pattern is CRTP. – wkl Oct 12 '16 at 17:15
  • @imnota4 Sure c++ templates can be restricted like Java generics, they are plenty more powerful... – Deduplicator Oct 12 '16 at 17:34
  • 2
    Look for std::enable_if_t and std::is_base_of. – Deduplicator Oct 12 '16 at 18:26
  • 2
    also look at std::is_arithmetic / std::is_integral / std::is_floating_point if what you are wanting to restrict is specifically numbers – Caleth Oct 13 '16 at 8:34
-2

For normal templates, you write:

template <typename T>

or

template <class T>

and this will accept any type.

Therefore, you should write:

template <size_t T>

And you effectively limit T to being a (decimal) number.

3
  • 1
    That's not accurate. I can still use a built in types even if I use class. – imnota4 Oct 14 '16 at 11:02
  • You're right: class is simply a recommendation in that case. The usage of using size_t or int64_t is, however, still a correct answer to the original question. – asger Oct 14 '16 at 11:25
  • Hmm, why is this down-voted? Isn't this exactly what the OP wants? – asger Dec 20 '16 at 12:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.