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:
<code>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.");
}
</code>
<code>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.");
}
</code>
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:
<code>'%': not valid as left operand has type 'T', with [T=const char *]
'/': not valid as left operand has type 'T', with [T=const char *]
...
</code>
<code>'%': not valid as left operand has type 'T', with [T=const char *]
'/': not valid as left operand has type 'T', with [T=const char *]
...
</code>
'%': 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.
Are there any alternatives? Or maybe there’s something I did wrong?
Any help is appreciated, thanks.
You need to use constexpr-if in your traits check:
<code>if constexpr (std::is_integral_v<T>)
// ^^^^^^^^^
</code>
<code>if constexpr (std::is_integral_v<T>)
// ^^^^^^^^^
</code>
if constexpr (std::is_integral_v<T>)
// ^^^^^^^^^