c++ 从正在示例化的crtp类型打印字符串

6yjfywim  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(89)

这是来自真实的代码的一个片段,但是我想在日志中打印服务类型。在这个例子中,我试图打印它,但我得到一个异常,我不知道为什么。我有其他使用编译时多态的方法,它们工作得很好。

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();

}
gwbalxhn

gwbalxhn1#

永远不要构造实现类 ServiceType1ServiceType2 的对象。
您只能构造服务器和服务类对象。
可能的选择之一是:

template <typename servicetype> class Service {
public:
    std::string& service_type() { 
        servicetype* pimpl = new servicetype;
        return pimpl->service_type_impl(); 
    }
};

但这完全取决于你想达到什么目的。
你需要更换

std::string&& service_type_;

std::string service_type_;

这样这个变量就可以真正复制传递的字符串。

相关问题