Type_triat and function template | Sololearn: Learn to code for FREE!

0

Type_triat and function template

Hi All Please find below code: https://code.sololearn.com/cA15a14a1A11 I though to have template function working only for int or float , but it is not working properly... Is there anything wrong or I am missing something?

2/19/2021 8:25:40 AM

Ketan Lalcheta

3 Answers

New Answer

+3

Ketan Lalcheta `is_integral` allows char as char is basically an integral type Quoted from en.cppreference.com/w/cpp/types/is_integral: "Checks whether T is an integral type. Provides the member constant value which is equal to true, if T is the type bool, char, char8_t, char16_t, char32_t, wchar_t, short, int, long, long long, or any implementation-defined extended integer types, including any signed, unsigned, and cv-qualified variants."

+3

You want the template function to work only for int or float, but your current code works for any type which is NOT int or float. This is because the condition you are passing to static_assert() is wrong. `!is_integral<T>::value && !is_floating_point<T>::value` will return true if T is neither int nor float. So if you pass in a type which is not integral or floating point, it will work because the condition will be true. Instead, the condition should be `is_integral<T>::value || is_floating_point<T>::value which will return true only if T is integral or floating point. Maybe you are confused about static_assert(). If the condition you pass into static_assert() is true, no error will occur, but if the condition is false, the program will fail to compile. https://en.cppreference.com/w/cpp/language/static_assert

0

Updated code now.... Still it is not throwing compiler error for char