문제

I would like to pass in some parameters into a curious repeating template pattern. I would then like this base class to create other objects and pass both types into the subclass. This would allow me to generalize the base class to perform some common logic before the subclass is called. Each subclass should be able to be a specialized instance of the one level hierarchy.

도움이 되었습니까?

해결책

Here is how to do this:

struct ParamOne {
    double val {0.0};
};

struct ParamTwo {
    int val {0};
};

template<typename P, typename Data, typename Other>
class Baseclass
{
public:
    using subclass_type = P;
    using data_type = Data;
    using other_type = Other;

    bool Method( const Data &data);
};

template<typename P, typename Data, typename Other> using pdata_type = typename P::data_type;
template<typename P, typename Data, typename Other> using pother_type = typename P::other_type;

template<typename P, typename Data, typename Other>
bool Baseclass<P, Data, Other>::Method( const Data &data )
{
    P& Subclass = static_cast<P&>( *this );
    pother_type<P, Data, Other> other;
    other.val = 11;

    return Subclass.SubclassMethod( data, other );
}

template<typename Data, typename Other>
class Subclass : public Baseclass<Subclass<Data, Other>, Data, Other>
{
public:
    using data_type = Data;
    using other_type = Other;

    bool SubclassMethod( const Data &data, Other &other );
};

template<typename Data, typename Other>
bool Subclass<Data, Other>::SubclassMethod( const Data &data, Other &other )
{
    return true;
}

template<>
bool Subclass<ParamOne, ParamTwo>::SubclassMethod( const ParamOne &data, ParamTwo &other )
{
    return true;
}

int main(int argc, char **argv)
{
    ParamOne one;
    one.val = 5.0;

    Subclass<ParamOne, ParamTwo> test;

    test.Method(one);
    return 0;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top