1

I have a bunch of overloaded functions to take on specific int sizes, float, double, char and std::string.

eg:

#include <cstdint>
#include <iostream>
void some_func(uint8_t& src) {
    std::cout << "inside uint8_t" << std::endl;
}
void some_func(uint16_t& src) {
    std::cout << "inside uint16_t" << std::endl;
}
void some_func(uint32_t& src) {
    std::cout << "inside uint32_t" << std::endl;
}
void some_func(uint64_t& src) {
    std::cout << "inside uint64_t" << std::endl;
}
void some_func(bool& src) {
    std::cout << "inside bool" << std::endl;
}
void some_func(double& src) {
    std::cout << "inside double" << std::endl;
}
void some_func(float& src) {
    std::cout << "inside float" << std::endl;
}
void some_func(const char& src) {
    std::cout << "inside char" << std::endl;
}
int main() {
    some_func((bool)true);
    some_func((double)13.4);
    return 0;
}

For some reason the overloaded const char& src function is called instead of double and bool. They both have explicit function overloads written, so why is the compiler promoting? moreover double is 64bits, so how is that being coverted to char? Can I solve this with template specialization? (I need to perform specifc actions depending on the data type)

Note: I am on Visual studio 2019 compiling with std=c++17

3
  • 2
    Your assumed calls do not include a dest.
    – jxh
    May 14, 2021 at 7:16
  • @t348575 Provide a minimal complete program that demonstrates the problem. May 14, 2021 at 7:16
  • 1
    The cast in (bool)true is redundant. May 14, 2021 at 13:00

1 Answer 1

6

Non-const lvalue references can't be initialized with rvalues. (bool)true; and (double)3.14 are rvalues.

The only overload with a const lvalue reference parameter (which can be initialized with rvalues) is the const char& src one, that's why it's used.

Since the type is different (char vs bool/double), a temporary char is created from the argument, and then is bound to the reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.