Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c++ is_integral_v<T> doesn't compile with templates

I want to declare a self-defined printing function to speed up std::cout when dealing with integer types. However, the code below doesn’t compile:

template <typename T>
static inline void print(T value)
{
    if (std::is_integral_v<T>)
    {
        if (value < 0) putchar('-'), value = -value;
        if (value > 9) print(value / 10);
        putchar(value % 10 + '0');
    }
    else std::cout << value;
}

int main()
{
    print("This is not an integer type.");
}

Compile error message:

'%': not valid as left operand has type 'T', with [T=const char *]
'/': not valid as left operand has type 'T', with [T=const char *]
...

But in fact, is_integral_v<const char*> is false so (theoretically) it can run perfectly in runtime.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Are there any alternatives? Or maybe there’s something I did wrong?

Any help is appreciated, thanks.

>Solution :

You need to use constexpr-if in your traits check:

if constexpr (std::is_integral_v<T>)
// ^^^^^^^^^

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading