mickydint
mickydint

Reputation: 11

c++ Template not identifying type double

I have just studied c++ templates and it was great that the books example compiled and worked. Then in the exercises at the end of the chapter I tried my own template programme. The code simple passes an array to the template function and it determines the largest value in the array. The problem is that when the type double array is passed the template is treating it as type int and displaying 5 as the larges value and not 5.0.

Here is my code

// Exercise 5.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>

template <typename T>
T max5(const T array[]);

int main()
{
    using std::cout;
    using std::cin;
    using std::endl;

    int intA[5]{ 1, 2, 5, 4, 3 };
    double doubleA[5]{ 1.0, 2.0, 5.0, 4.0, 3.0 };

    cout << "Max int " << max5(intA) << endl;
    cout << "Max double " << max5(doubleA) << endl;

    cin.get();
    cin.get();
    return 0;
}

template <typename T>
T max5(const T array[])
{
    T max = array[0];
    for (int i = 1; i < 5; i++)
    {
        if (array[i] > max) max = array[i];

        //std::cout << "Max: " << max << std::endl;
    }

    return max;
}

Any ideas as to why?

Regards

Mickydint

Upvotes: 0

Views: 378

Answers (1)

deW1
deW1

Reputation: 5660

You're getting the correct types back, the problem is with you displaying them.

cout << "int == "    << typeid(max5(intA)).name()    << endl;
cout << "double == " << typeid(max5(doubleA)).name() << endl;

std::cout has different ways of showing higher precision or different formatting.

Like:

std::setprecision
std::fixed
std::scientific
std::hexfloat
std::defaultfloat

and std::showpoint as Zulukas already pointed out.

// Exercise 5.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <typeinfo>

template <typename T>
T max5(const T array[]);

int main()
{
    using std::cout;
    using std::cin;
    using std::endl;

    int intA[5]{ 1, 2, 5, 4, 3 };
    double doubleA[5]{ 1.0, 2.0, 5.0, 4.0, 3.0 };

    cout << "int == "    << typeid(max5(intA)).name()    << endl;
    cout << "double == " << typeid(max5(doubleA)).name() << endl;

    cout << std::showpoint;
    cout << "Max int "    << max5(intA) << endl;
    cout << "Max double " << max5(doubleA) << endl;
    cout << std::noshowpoint;

    cout << std::fixed;
    cout << "Max int "    << max5(intA)    << endl;
    cout << "Max double " << max5(doubleA) << endl;

    cin.get();
    cin.get();
    return 0;
}

template <typename T>
T max5(const T array[])
{
    T max = array[0];
    for (int i = 1; i < 5; i++)
    {
        if (array[i] > max) max = array[i];

        //std::cout << "Max: " << max << std::endl;
    }

    return max;
}

Live

Upvotes: 1

Related Questions