C++模板通过 Enum 指定类型
我面临一个问题: 我想创建一个函数,它根据函数将接收的枚举来调用特定的模板类型构造函数。我的意思是:
typedef ____ (Class<whatever>::*tabType)(int flag);
template<typename T>
static Class* Class<t>::createClassInstance(enum precision)
{
static const ___ createTab[] = {
Class<int>,
Class<double>
}
return (new createTab[precision](1));
}
I'm facing a problem :
I want to create a function which calls a specific template type constructor depending on a enum that the function will receive. By that i mean :
typedef ____ (Class<whatever>::*tabType)(int flag);
template<typename T>
static Class* Class<t>::createClassInstance(enum precision)
{
static const ___ createTab[] = {
Class<int>,
Class<double>
}
return (new createTab[precision](1));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果枚举值作为函数参数是动态的,则必须使用调度表或 switch/if-else。请注意,您的伪代码没有清楚地解释要求。比如说,您到底想要定义什么 createInstance 函数以及如何调用它?
If the enum value is dynamic as a function argument, you'll have to use either a dispatch table or switch/if-else. Notice that your pseudo code does not clearly explain the requirement. Say, what exactly the createInstance function you wish to define and how is it going to be called?
我想说,只需构建一个将枚举映射到工厂函数(boost::function<>)的
std::map
即可。然后,您只需为所需的每种类型添加一个条目及其相应的enum
。实际构建工厂功能。您可以为每个类使用一些静态 Create() 函数并存储函数指针。或者,您可以使用 Boost.Lambda 构造函数/析构函数 函子。或者,您可以使用 Boost.Bind 来构造函子包装需要一定数量参数的工厂函数。这是一个例子:我可能犯了一些轻微的语法错误,但基本上你应该能够完成上述工作。此外,您拥有多个类模板的事实也不起作用,一旦将它们实例化为具体类(例如
Class
或Class
),它们就会就像任何其他类一样,上述想法应该仍然有效。I would say, just construct a
std::map
that maps theenum
to a factory function (boost::function<>
). Then you just add one entry for each type that you want, with its correspondingenum
. To actually construct the factory functions. You can either have somestatic Create()
function for each class and store a function pointer. Or, you can use Boost.Lambda constructor/destructor functors. Or, you can use Boost.Bind to construct functors that wrap a factory function that requires some number of parameters. Here is an example:I might have made some slight syntax mistakes, but basically you should be able make the above work. Also, the fact that you have several class templates plays no role, once they are instantiated to a concrete class (like
Class<int>
orClass<double>
) they are just like any other class, and the above idea should remain valid.扩展您的示例,类似于以下内容:
Extending your example, something like the following works:
实现此类事情的方法有很多种,但听起来您想要创建一个工厂方法数组(或映射)(每个类一个),由
enum
变量索引。每个都调用相关的构造函数,并返回该类型的新对象。当然,为了使这一点有意义,所有类都必须派生自一个共同的基础。
There are a number of ways of achieving this sort of thing, but it sounds like you want to create an array (or map) of factory methods (one for each class), indexed by the
enum
variable. Each one calls the relevant constructor, and returns a new object of that type.Of course, for this to make any sense, all of the classes must derive from a common base.