如何解决在运行时更改模板参数C ++
我有一个庞大而复杂的程序,该程序相当广泛地使用模板。 为了简单起见,请考虑在我的程序中有以下类:
铜叉,银叉,金叉
单刀,锯齿刀,黄油刀
RedSpoon,GreenSpoon,BlueSpoon
然后在main.cpp中调用一个函数:
Eating<BronzeFork,SerratedKnife,BlueSpoon>::runEat();
我的目标是能够在运行时将参数提供给我的(编译的)程序,以便修改此运行中所需的叉子或勺子的类型。
我可以使用一个非常大的switch语句来执行此操作,该语句运行叉子,刀子和汤匙的每种组合,但是它看起来很杂乱,令人费解并且难以维护。 尤其是因为我不断向程序中添加各种叉子,刀子和勺子。
以一种干净,有效的方式做到这一点的最佳方法是什么?
解决方法
C ++是一种可编译的语言,这意味着必须在代码生成时就知道类型。虚拟类可以解决您的问题。
这与模板的使用不兼容,模板可以使源代码紧凑。但是必须实例化所有可以在运行时满足的类型的专业化。
,这不一定是解决问题的最佳方法。这是一种以紧凑方式生成大量实例的方法。它可能适合您,也可能不适合您。
我假设您的每个类都有一个用于运行时选择的ID,例如一个字符串。因此BronzeFork::id
将是"BronzeFork"
。此后,我将使用缩写名称。
#include <tuple>
#include <string>
#include <functional>
#include <map>
struct F1 { static constexpr const char* id = "F1"; };
struct F2 { static constexpr const char* id = "F2"; };
struct F3 { static constexpr const char* id = "F3"; };
struct K1 { static constexpr const char* id = "K1"; };
struct K2 { static constexpr const char* id = "K2"; };
struct K3 { static constexpr const char* id = "K3"; };
struct S1 { static constexpr const char* id = "K1"; };
struct S2 { static constexpr const char* id = "K2"; };
struct S3 { static constexpr const char* id = "K3"; };
template <typename F,typename K,typename S> struct Eater
{
static void eat();
};
using t3 = std::tuple<std::string,std::string,std::string>;
std::map<t3,std::function<void()>> funcMap;
现在,我们需要填充funcMap
。我们需要嵌套的编译时循环。我使用fold-expressions将它们实现为单独的模板。也许有更好的方法,但是这种方法非常简单明了,因此很容易理解。
template <typename F,typename S> struct populate0
{
void operator()() { funcMap.insert({{F::id,K::id,S::id},Eater<F,K,S>::eat}); }
};
// Inner loop
template <typename Fs,typename S> struct populate1;
template <typename ... Fs,typename S>
struct populate1 <std::tuple<Fs...>,S> // loop over Fs
{
void operator()() { (populate0<Fs,S>()(),...); }
};
// Middle loop
template <typename Fs,typename Ks,typename S> struct populate2;
template <typename Fs,typename ... Ks,typename S>
struct populate2 <Fs,std::tuple<Ks...>,S> // loop over Ks
{
void operator()() { (populate1<Fs,Ks,...); }
};
// Outer loop
template <typename Fs,typename Ss> struct populate3;
template <typename Fs,typename... Ss> // loop over Ss
struct populate3 <Fs,std::tuple<Ss...>>
{
void operator()() { (populate2<Fs,Ss>()(),...); }
};
现在我们只需要运行循环。
populate3<std::tuple<F1,F2,F3>,std::tuple<K1,K2,K3>,std::tuple<S1,S2,S3>>()();
无论何时添加另一个类,都将其添加到此调用中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。