c++crtpstatic-polymorphism

Print string from crtp type being instanciated


This a snippet from the real code, but the idea is that i want to print the service type in my log. In this example i'm trying to print it, but i get an exception, and i don't know why. I have other methods using compile-time polymorphism which are working fine.

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

}

Solution

  • You never construct objects of your implementation classes ServiceType1 and ServiceType2.

    You construct only Server and Service class objects.

    One of possible options would be:

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

    but it totally depends on what you want to achieve.

    And you need to replace

    std::string&& service_type_;
    

    to

    std::string service_type_;
    

    in both your derived classes so that this variable could really make a copy of the passed string.