SaidAlbahri
SaidAlbahri

Reputation: 11

How to pass strcut Datatype into template?

I have two template classes that inherits from each other. And I have a struct Date that I want to pass into a function in one of the classes but I get this error when I compile:

no operator found which takes a right-hand operand of type 'Date' (or there is no acceptable conversion)

The error is in line 95 specifically.

As you can see in my code, I am passing different data types to test if the function works. All of them worked perfectly except struct Date.

What am I doing wrong?

my code:

#include <iostream>
#include <string>
using namespace std;

template <typename T> class B;     //forward declare

template <typename T>
class A
{
    T valuea;
public:
    A(){};
    T getValuea()
    {
        return valuea;
    }

    void setValuea(T x)
    {
        valuea = x;
    }
    A(const A &x)
    { 
        valuea = x.valuea; 
    }

    friend class B<T>;     //A<int> is a friend of B<int> 
};

template <typename T>
class B : A<T>
{
    T valueb;
public:
    using A<T>::setValuea;
    using A<T>::getValuea;
    B(){};
    T getValueb()
    {
        return valueb;
    }
    void setValueb(T x)
    {
        valueb = x;
    }
    B(const B &x)
    {
        valueb = x.valueb;
        this->valuea = x.valuea;
    }
};

struct Date
{
    int day;
    int month;
    int year;
};

int main()
{
    B<float> b;
    b.setValuea(1.34);
    b.setValueb(3.14);

    cout << "b.setValuea(1.34): " << b.getValuea() << endl
        << "b.setValueb(3.14): " << b.getValueb() << endl;

    B<int> a;
    a.setValuea(1);
    a.setValueb(3);

    cout << "a.setValuea(1): " << a.getValuea() << endl
        << "a.setValueb(3): " << a.getValueb() << endl;

    B<char> y;
    y.setValuea('a');
    y.setValueb('c');

    cout << "y.setValuea('a'): " << y.getValuea() << endl
        << "y.setValueb('c'): " << y.getValueb() << endl;

    B<string> u;
    u.setValuea("good");
    u.setValueb("morning");

    cout << "u.setValuea(good): " << u.getValuea() << endl
        << "u.setValueb(morning): " << u.getValueb() << endl;

    B<Date> p;
    p.setValuea({ 27, 10, 2014 });
    p.setValueb({ 2, 11, 2014 });

    cout << "p.setValuea({ 27, 10, 2014 }): " << p.getValuea() << endl
         << "p.setValueb({ 2, 11, 2014 }):  " << p.getValueb() << endl;


    system("Pause");
    return 0;
}

Upvotes: 0

Views: 81

Answers (1)

Neil Kirk
Neil Kirk

Reputation: 21773

You need to provide an operator<< for your Date class, otherwise it doesn't know how to output it to a stream. You could try the following:

struct Date
{
    int day;
    int month;
    int year;

    friend ostream& operator << (ostream& os, const Date& date)
    {
        return os << "Day: " << date.day << ", Month: " << date.month << ", Year: " << date.year << " ";
    }
};

Live example: http://ideone.com/ehio6Q

Upvotes: 1

Related Questions