Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make sure that template type is a number type?

Tags:

c++

templates

How can I sure that the type passed to my template function is a numeric type?

Here is my function:

template <typename T>
T toStdNumber()
{
  type_info t_info = typeid(T);
  /* ... Converting my class to T if it's numeric type ... */
}

I must do this within the 2003 standard, so <type_traits> isn't a solution.

like image 835
anion155 Avatar asked Dec 02 '25 21:12

anion155


2 Answers

A static assertion should do the trick:

#include <type_traits>

template <typename T>
T toStdNumber()
{
    static_assert(std::is_arithmetic<T>::value, "Not an arithmetic type");
    // ...
}

See cppreference for the taxonomy of types.

like image 187
Kerrek SB Avatar answered Dec 04 '25 10:12

Kerrek SB


Since I have not found a concise solutions for C++03, I decide to use this creepy construction

if (
    typeid(T) != typeid(short int) &&
    typeid(T) != typeid(int) &&
    typeid(T) != typeid(long int) &&
    typeid(T) != typeid(long long int) &&
    typeid(T) != typeid(unsigned short int) &&
    typeid(T) != typeid(unsigned int) &&
    typeid(T) != typeid(unsigned long int) &&
    typeid(T) != typeid(unsigned long long int)
  )
  throw bad_typeid();
like image 45
anion155 Avatar answered Dec 04 '25 10:12

anion155



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!