I am trying to create two functions both named maximum (which overload each other) that compute the maximum of two arguments. The first should find maximum of two arguments of type double. The second should accept two arguments of type string (not C-string types) and should return the argument that comes alphanumerically second.

Intuitively I would think template in C++ but I try such and it failed. Any suggestions? trial code below:

template<class T>
T maximum(T first, T second){
    if (first < second){
        return second;}
    else{
        return first;}}


int main ()
{
  int i = 1, j = 2, k;
    k = maximum(i, j);
    cout << k << endl;
    char a[] = "llll" , b[] = "b", c[3];
    cout << maximum(b ,a)<< endl;
    system("PAUSE");
    return 0;
}

This seems to work somewhat

template<class T>
T maximum(T& first, T& second){
    if (first < second){
        return second;}
    else{
        return first;}}


int main ()
{
    int i = 1, j = 2, k;
    k = maximum(i, j);
    cout << k << endl;
    char a[] = "c" , b[] = "b";
    cout << maximum(*b ,*a)<< endl;
    system("PAUSE");
    return 0;
}

In your first post, when comparing two char pointers, you'll return the one with the higher memory address. In the second post, you're just comparing the first character of each string, which will return whichever character is alphabetically greater, though it's still not going to perform a string comparison.
I think you're just going to have to write the overloaded functions and define the data type, in order to perform the correct type of comparison.

[...] The second should accept two arguments of type string (not C-string types) [...]

Why do you use C-strings in your code then?

[...] Intuitively I would think template in C++ [...]

You're right. Your maximum function template works fine for both doubles and std::strings. Also, as nullptr noticed, you'll have to write an overload if you want your function to behave properly for C-strings.

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

template <class T>
T maximum(T first, T second)
{
    cout << "(using function template) ";

    return first > second ? first : second;
}

const char * maximum(const char * first, const char * second)
{
    cout << "(using const char * overload) ";

    return strcmp(first, second) > 0 ? first : second;
}

int main()
{
    cout << maximum(5, 2) << endl;
    cout << maximum(7L, 3L) << endl;
    cout << maximum(1.2, 3.4) << endl;
    cout << maximum(2.3f, 5.5f) << endl;
    cout << maximum("abc", "abd") << endl;
    cout << maximum(string("abc"), string("abd")) << endl;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.