gpt4 book ai didi

c++ - 将特化定义为另一个类的实例化

转载 作者:太空狗 更新时间:2023-10-29 22:59:24 24 4
gpt4 key购买 nike

我有一种情况,我想定义一个特化,使其另一个类的实例化相同。这是我想要的一个简单示例(此示例中的完整实例化;在我的实际问题中,我想要部分特化):

//Template class
template <int i> class Foo { /*...*/ };

//Another, completely different, template class
template <int i,int j> class Bar { /*...*/ };

//Ordinary specialization of Foo
template <> class Foo<0> { /*...*/ };

//Bogus specializations of Foo that
// hopefully explain what I want.
template <> class Foo<1> = Bar<1, 11>;
template <> class Foo<2> = Bar<2, 42>;
template <> class Foo<3> = Bar<3,-71>;
...

这样做有什么好处? Foo<1>的定义, Foo<2>等相当复杂,但很容易作为模板编写一次。有很多这样的定义。处理 Bar 的定义进入Foo不是一个选择。只有一些值可以特化,特化Bar必须手动选择(因此 int j 的随机数)。

我通常会使用 CRTP 来实现这种效果。我会对 Bar 做一些相当讨厌的修改,然后做类似的事情:

template <> class Foo<1> : public Bar<1, 11,Foo<1>> {};
template <> class Foo<2> : public Bar<2, 42,Foo<2>> {};
template <> class Foo<3> : public Bar<3,-71,Foo<3>> {};
...

显然,Bar需要改变,也许有一些using拉下构造函数的声明。这会很麻烦。

我的问题:我能做得更好吗?也就是说,是否可以将特化定义为另一个模板类的实例化?


注意:首选标准是 C++14,但更高版本也是可以接受的。

最佳答案

间接寻址在这里有帮助吗? :)

template<int i> struct Indirection { using type = Foo<i>; };

template <> class Indirection<1> { using type = Bar<1, 11>; };
template <> class Indirection<2> { using type = Bar<2, 42>; };
template <> class Indirection<3> { using type = Bar<3, -71>; };

template<int i>
using ActualFoo = typename Indirection<i>::type;

关于c++ - 将特化定义为另一个类的实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36928775/

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