gpt4 book ai didi

c++ - 我如何使用和专门化 'curious repeating template pattern'

转载 作者:太空宇宙 更新时间:2023-11-04 13:57:55 25 4
gpt4 key购买 nike

我想将一些参数传递到一个奇怪的重复模板模式中。然后我希望这个基类创建其他对象并将这两种类型传递给子类。这将允许我在调用子类之前概括基类以执行一些通用逻辑。每个子类都应该能够成为一级层次结构的专门实例。

最佳答案

这是如何做到这一点:

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;
}

关于c++ - 我如何使用和专门化 'curious repeating template pattern',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20618822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com