C++ templates (error for Class own reference)...
Posted: Thu May 19, 2011 5:43 am
Dear All,
I am receiving error for the below code
For the line number 31:
I am getting the below errors, let me know why?
However, the below program is working fine without Template
I am receiving error for the below code
Code: Select all
#include <iostream>
using namespace std;
template <class T>
class class_template
{
T value1;
T value2;
public:
class_template (T first, T second)
{
value1 = first;
value2 = second;
}
// public function
T getmax()
{
return value1 > value2 ? value1 : value2;
}
};
int main()
{
char a = 'A', b = 'B';
class_template <int> myobject1 (100, 75);
class_template <int> myobject2 (123.123, 75.87);
class_template <float> myobject3 (123.123, 75.87);
class_template <char> myobject4 ('A', 10);
class_template <char*> myobject5 (&a, &b);
class_template <class_template*> myobject6 ((class_template*)0x100, (class_template*)0x200);
cout << "\n Maximum Value (int)= " << myobject1.getmax();
cout << "\n Maximum Value (int)= " << myobject2.getmax();
cout << "\n Maximum Value (float)= " << myobject3.getmax();
cout << "\n Maximum Value (char)= " << myobject4.getmax();
printf("\n Maximum Value (char*)= 0x%08X [a=0x%08X, b=0x%08X]", myobject5.getmax(), &a, &b);
printf("\n Maximum Value (class_template*)= 0x%08X [a=0x%08X, b=0x%08X]", myobject6.getmax(), &myobject1, &myobject2);
cout << "\n";
return 0;
}
Code: Select all
class_template <class_template*> myobject6 ((class_template*)0x100, (class_template*)0x200);
Code: Select all
error: template argument 1 is invalid
error: invalid type in declaration before ‘(’ token
error: missing template arguments before ‘*’ token
error: expected primary-expression before ‘)’ token
error: missing template arguments before ‘*’ token
error: expected primary-expression before ‘)’ token
error: initializer expression list treated as compound expression
Code: Select all
#include <iostream>
using namespace std;
//template <class T>
class class_template
{
class_template* value1;
class_template* value2;
public:
// Constructor
class_template (class_template* first, class_template* second)
{
value1 = first;
value2 = second;
}
// public function
unsigned long getmax()
{
return (unsigned long)(value1 > value2 ? value1 : value2);
}
};
int main()
{
class_template myobject1((class_template*)0x10, (class_template*)0x20);
class_template myobject2((class_template*)0x30, (class_template*)0x40);
class_template myobject3(&myobject1, &myobject2);
printf("\n Maximum Value (class_template*)= 0x%08X [a=0x%08X, b=0x%08X]", myobject3.getmax(), &myobject1, &myobject2);
cout << "\n";
return 0;
}
/*
output:
Maximum Value (class_template*)= 0xBFBE87A8 [a=0xBFBE87A8, b=0xBFBE87A0]
*/