Below snippet 1 worked as desired. However when I tried to to covert Sender to a templated one (snippet 2), I keep getting compiler errors. The goal is to get this working with minimal changes, so preferable keep the <double>
and <int>
specific implementations, but keep DUMMY
generic. Is this possible?
Snippet 1: Untemplated Sender -> Works
#include <iostream>
class Sender {
public:
void send(double d) const {
std::cout <<"Send double "<<d<<std::endl;
}
void send(int i) const {
std::cout << "Send int "<<i<<std::endl;
}
};
template<typename T>
class DataObject {
T data;
public:
DataObject(T ldata) : data(ldata) {}
void send(const Sender& s);
};
template<>
void DataObject<double>::send(const Sender& sender) {
sender.send(data);
}
template<>
void DataObject<int>::send(const Sender& sender) {
sender.send(data);
}
int main() {
Sender sender;
DataObject<double> obj(1.0);
DataObject<int> obj2(2);
obj.send(sender);
obj2.send(sender);
return 0;
}
Snippet 2: Templated Sender -> Compiler Errors
#include <iostream>
template<typename DUMMY>
class Sender {
DUMMY dummy;
public:
Sender(const DUMMY& ldummy) : dummy(ldummy) {}
void send(double d) const {
std::cout << dummy <<" - Send double "<<d<<std::endl;
}
void send(int i) const {
std::cout << dummy << " - Send int "<<i<<std::endl;
}
};
template<typename T,typename DUMMY>
class DataObject {
T data;
public:
DataObject(T ldata) : data(ldata) {}
void send(const Sender<DUMMY>& s);
};
template<typename DUMMY>
void DataObject<double>::send(const Sender<DUMMY>& sender) {
sender.send(data);
}
template<typename DUMMY>
void DataObject<int>::send(const Sender<DUMMY>& sender) {
sender.send(data);
}
int main() {
Sender<std::string> sender("Dummy");
DataObject<double> obj(1.0);
DataObject<int> obj2(2);
obj.send(sender);
obj2.send(sender);
return 0;
}
Aucun commentaire:
Enregistrer un commentaire