I have a simple cpp template function as follows.
#include <iostream>
#include <concepts>
template <typename T> requires std::integral<T>
T add(T a, T b)
{
std::cout << "From within the function, typeid(T).name(): " << typeid(T).name() << std::endl;
std::cout << "From within the function, typeid(a).name(): " << typeid(a).name() << std::endl;
return a + b;
}
Now from main, I call it as follows.
int main()
{
char a_0{10};
char a_1{20};
std::cout << "typeid(a_0).name(): " << typeid(a_0).name() << std::endl;
auto result_a = add(a_0, a_1);
std::cout << "result_a : " << static_cast<int>(result_a) << std::endl;
}
I am expecting a compilation error because while the type parameters are constrained to be integral, I am passing char arguments.
Why is it working?
I compiled with the following command.
g++ "-static" -o main.exe .\*.cpp -std=c++20
I get the following output.
typeid(a_0).name(): c
typeid(T).name(): c
typeid(a).name(): c
result_a : 30
I am expecting a compilation error because while the type parameters are constrained to be integral, I am passing
chararguments.Why is it working?
Because char is considered an integral type in C++.
From cppreference.com, the std::is_integral :
template< class T > struct is_integral; (since C++11)
std::is_integralis a UnaryTypeTrait.Checks whether
Tis an integral type. Provides the member constant value which is equal to true, ifTis the type bool,char,char8_t(since C++20),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. Otherwise, value is equal to false.
Therefore, if you want to restrict your function to work only with larger integer types and exclude char, you could modify your constraint accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With