Reputation: 314
This is what my code looks like. It is a bit simplified. What I'm trying to/wondering if i can do is eliminate the need for the argument in the property class constructor. i.e. call a no arg constructor and still be able to populate the classes item variable with the struct value1 item variable without adding them as part of the constructors body.
#include <iostream>
using namespace std;
struct value1
{
const int item;
value1( int n ) : item(n) { }
};
struct value2 : public value1
{
value2() : value1(55) { };
};
template <class T>
class property
{
public:
property(T stuff);
void print();
private:
int item;
};
template <class T>
property<T>::property(T stuff) : item(stuff.item) { }
template <class T>
void property<T>::print()
{
cout << item << endl;
}
int main()
{
property<value2> *y = new property<value2>(value2());
y->print();
return 0;
}
Upvotes: 1
Views: 56
Reputation: 12731
You can achieve using function objects. Please find code below:
struct value1
{
const int item;
value1( int n ) : item(n) { }
};
struct value2 : public value1
{
value2() : value1(55) { };
};
template <class T>
class property
{
public:
property();
void operator() (T i)
{
item = i.item;
}
void print();
private:
int item;
};
template <class T>
property<T>::property() { }
template <class T>
void property<T>::print()
{
cout << item << endl;
}
int main()
{
property<value2> *y = new property<value2>();
(*y)(value2());
y->print();
return 0;
}
Upvotes: 0
Reputation: 50540
call a no arg constructor and still be able to populate the classes item variable with the struct value1 item variable without adding them as part of the constructors body
It sounds like you simply want a factory method:
template <class T>
class property {
public:
property();
void print();
static property<T> create(T stuff) {
property<T> p;
p.item = stuff.item;
return p;
}
private:
int item;
};
You can invoke it as it follows:
auto p = property<value2>::create(value2());
Even if I'm not sure I got exactly what your requirements are.
Let me know and I'll delete the answer if I didn't understand the question.
Upvotes: 1