gpt4 book ai didi

c++ - 通过枚举模板化的类调用方法

转载 作者:行者123 更新时间:2023-11-30 01:30:50 25 4
gpt4 key购买 nike

给定以下代码:

enum Fruits{ eApple, eBanana };

template<>
struct SomeFruit< eApple > {
void eatIt() { // eat an apple };
};

template<>
struct SomeFruit< eBanana > {
void eatIt() { // eat a banana };
};

有没有办法为每个 Fruits 调用显式专用的 eatIt(),而无需手动进行每次调用?

我对“手动进行每次调用”的定义是:

void eatAllFruits()
{
SomeFruit< eApple > apple;
apple.eatIt();
SomeFruit< eBanana > banana;
banana.eatIt();
}

显然,使用这种方法,每次修改 Fruits 时都必须扩展 eatAllFruits

最佳答案

此时我的猜测是您想自动迭代枚举水果。事实上,有一种方法可以做到这一点。看看我在博客上写的这篇关于类似问题的文章:http://crazyeddiecpp.blogspot.com/2010/02/using-mplforeach-to-fill-tuple.html

注意 mpl::range 和 mpl::for_each 的使用。

因此你的 eatSomeFruit() 函数看起来像这样:

// modify enum...
enum Fruits { eApple, eBananna, eFruitLast = eBananna };

struct eat_fruit
{
template < typename Index >
void operator() (Index&)
{
SomeFruit<Index::value> eater;
eater.eatIt();
}
};

void eatSomeFruit()
{
mpl::for_each< mpl::range<0, eFruitLast> >(eat_fruit());
}

关于c++ - 通过枚举模板化的类调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4035088/

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