Search code examples
c++sizeoftype-promotion

The standard way to get sizeof(promoted(x))


Is there a standard way to get the size of the type a variable would be promoted to when passed as a variadic argument?

auto x = ...;
auto y = sizeof(promoted(x));

The results should be:

char  -> sizeof(int)
int   -> sizeof(int)
float -> sizeof(double)
...

Solution

  • We can simply declare overloaded promoted functions with the proper types:

    int promoted(char);
    int promoted(short);
    int promoted(int);
    long promoted(long);
    long long promoted(long long);
    double promoted(float);
    double promoted(double);
    long double promoted(long double);
    

    Note that the functions need no implementations, because we are never actually calling them.

    Here is a simple test run which prints 1, 4 and 4, 8 on my machine:

    std::cout << sizeof('a') << '\n';
    std::cout << sizeof(promoted('a')) << '\n';
    
    std::cout << sizeof(3.14f) << '\n';
    std::cout << sizeof(promoted(3.14f)) << '\n';