Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a function using template for data type not supposed to return long long int?

Tags:

c++

templates

I'm new to c++ and I've written a function which takes a and b as input and returns a raised to the power of b. I used templates for the function return data type and data type for a. but it fails to return the correct result for large numbers. I tried calculating pow(2,50) and it returns 0.

template <class numeric_type>
numeric_type pow(numeric_type a, int b) {
    numeric_type result = 1;
    for (int i = 0; i < b; i++) {
        result *= a;
        cout << result << i << endl;
    }
    return result;
}

And inside the main:

long long int powered = pow(2, 50);
cout << powered;
like image 684
Arian Hassani Avatar asked Jan 21 '26 10:01

Arian Hassani


2 Answers

Yeah, that wont work. The numeric type of '2' is int. Use '2LL' for a long long int. The reason this isn't working is because 2^50 is too big to store within an integer (it's a 32bit number, but you would need 51bits to store 2^50)

auto powered = pow(2LL, 50);

like image 132
robthebloke Avatar answered Jan 25 '26 19:01

robthebloke


Template arguments are deduced from function arguments being passed (but not return type); so given pow(2, 50);, numeric_type is deduced as int.

You can specify numeric_type explicitly,

auto powered = pow<long long int>(2, 50); // specify numeric_type as long long int explicitly

or add an explicit conversion on 2 to make it a long long int.

auto powered = pow(static_cast<long long int>(2), 50); // numeric_type is deduced as long long int
like image 26
songyuanyao Avatar answered Jan 25 '26 20:01

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!