Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why template function which is constrained to work with integrals, is working fine with char as well? [duplicate]

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
like image 980
VivekDev Avatar asked Dec 08 '25 08:12

VivekDev


1 Answers

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?

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_integral is a UnaryTypeTrait.

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(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.

like image 185
JeJo Avatar answered Dec 10 '25 06:12

JeJo