C++ Templet qustion....
May 2, 2008 at 7:14pm UTC
Can you please help me with following c++ Templet question ?
But when you try to use the two together:
the compiler gives a lot of rather indecipherable error messages, telling you:
could not deduce template argument for 'const class td::basic_string<_E,_Tr,_A>' from 'class Ingredient'
and so on.
What's the problem? How would can i fix it?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
// add.h
template <class TYPE>
TYPE add(TYPE &a, TYPE &b)
{
return a + b;
}
// ingredient.h
#include <string>
using namespace std;
class Ingredient
{
public :
Ingredient(double amount, string unit)
: m_amount(amount), m_unit(unit)
{}
private :
double m_amount;
string m_unit;
};
#include <iostream>
using namespace std;
#include "ingredient.h"
#include "add.h"
int main()
{
Ingredient oil(3, "gallons" );
Ingredient water(2, "gallons" );
Ingredient result = add(oil, water);
return 0;
}
Last edited on May 2, 2008 at 7:48pm UTC
May 2, 2008 at 7:15pm UTC
Please help me..
May 2, 2008 at 7:33pm UTC
You need to overload operator+ for Ingredient.
1 2 3 4 5
class Ingredient {
friend Ingredient operator +( Ingredient const & i1, Ingredient const & i2 ) {
// Add them together and return result;
}
};
Otherwise the compiler does not know how to perform a + b in add() with
TYPE=Ingredient.
May 2, 2008 at 8:23pm UTC
JSmith.....
This strategy doesnt work....try to plug in code....It keep on erroring..
May 3, 2008 at 4:54am UTC
The following code compiles fine for me using
g++ (GCC) 4.1.1 20070105 (Red Hat 4.1.1-51)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include <iostream>
using namespace std;
template <class TYPE>
TYPE add(TYPE &a, TYPE &b)
{
return a + b;
}
class Ingredient
{
public :
Ingredient(double amount, string unit)
: m_amount(amount), m_unit(unit)
{}
// Function I added:
friend Ingredient operator +( const Ingredient&, const Ingredient& ) {}
private :
double m_amount;
string m_unit;
};
int main()
{
Ingredient oil(3, "gallons" );
Ingredient water(2, "gallons" );
Ingredient result = add(oil, water);
return 0;
}
Topic archived. No new replies allowed.