这是来自真实的代码的一个片段,但是我想在日志中打印服务类型。在这个例子中,我试图打印它,但我得到一个异常,我不知道为什么。我有其他使用编译时多态的方法,它们工作得很好。
template <typename servicetype> class Service {
public:
std::string& service_type() { return static_cast<servicetype*>(this)->service_type_impl(); }
};
class ServiceType1 : public Service<ServiceType1> {
public:
ServiceType1() :service_type_("Service Type 1") {}
std::string& service_type_impl() { return service_type_; }
private:
std::string&& service_type_;
};
class ServiceType2 : public Service<ServiceType2> {
public:
ServiceType2() :service_type_("Service Type 2") {}
std::string& service_type_impl() { return service_type_; }
private:
std::string&& service_type_;
};
template <typename T>
class Server
{
public:
void print() {
std::cout << service_.service_type()<<std::endl;
}
Service<T> service_;
};
int main()
{
Server<ServiceType1> service_type1;
Server<ServiceType2> service_type2;
service_type1.print();
service_type2.print();
}
1条答案
按热度按时间gwbalxhn1#
永远不要构造实现类 ServiceType1 和 ServiceType2 的对象。
您只能构造服务器和服务类对象。
可能的选择之一是:
但这完全取决于你想达到什么目的。
你需要更换
到
这样这个变量就可以真正复制传递的字符串。