简体   繁体   English

有没有办法在模板类中处理可变数量的参数?

[英]Is there a way to handle a variable number of parameters in a template class?

I have a set of callback classes that I use for handling callbacks with variable numbers of parameters. 我有一组回调类,用于处理具有可变数量参数的回调。 Right now I have about 6 different instances of it to handle differing numbers of arguments. 现在我有大约6个不同的实例来处理不同数量的参数。 Is there a way to make one instance than can handle a variable number of arguments?? 有没有办法使一个实例可以处理可变数量的参数? Ultimately I would love to have each parameter be a POD type or a class pointer, or a struct pointer. 最后,我希望每个参数都是POD类型或类指针,或结构指针。 Any ideas? 有任何想法吗?

template <class T>
class kGUICallBackPtr
{
public:
    kGUICallBackPtr() {m_obj=0;m_func=0;}
    void Set(void *o,void (*f)(void *,T *));
    inline void Call(T *i) {if(m_func) m_func(m_obj,i);}
    inline bool IsValid(void) {return (m_func!=0);}
private:
    void *m_obj;
    void (*m_func)(void *,T *);
};


template <class T,class U>
class kGUICallBackPtrPtr
{
public:
    kGUICallBackPtrPtr() {m_obj=0;m_func=0;}
    void Set(void *o,void (*f)(void *,T *,U *));
    inline void Call(T *i, U *j) {if(m_func) m_func(m_obj,i,j);}
    inline bool IsValid(void) {return (m_func!=0);}
private:
    void *m_obj;
    void (*m_func)(void *,T *,U *j);
};

还没有语言本身,但C ++ 0x将支持可变参数模板

C++0x variatdic templates is your best bet, but it will also be a while before you can use them. C ++ 0x variatdic模板是你最好的选择,但它还需要一段时间才能使用它们。

If you need sequences of types today, take a look at MPL's vector of types, as well as other type sequence types. 如果您今天需要类型序列,请查看MPL的类型向量以及其他类型的序列类型。 It's part of the Boost library. 它是Boost库的一部分。 It allows you to provide a template argument that is a sequence of types, instead of just a single type. 它允许您提供模板参数,该参数是一系列类型,而不仅仅是单一类型。

My first choice would be to use boost::bind, boost::function, or std::bind/std::function and/or c++11 lambda's to achieve your goal. 我的第一选择是使用boost :: bind,boost :: function或std :: bind / std :: function和/或c ++ 11 lambda来实现你的目标。 But if you need to roll your own functor then I would use boost fusion to create a 'fused functor' that takes a single template argument. 但是如果你需要滚动自己的仿函数,那么我会使用boost fusion来创建一个带有单个模板参数的“融合仿函数”。

http://www.boost.org/doc/libs/1_41_0/libs/fusion/doc/html/fusion/functional/generation/functions/mk_fused.html http://www.boost.org/doc/libs/1_41_0/libs/fusion/doc/html/fusion/functional/generation/functions/mk_fused.html

Ultimately all of these libraries use pre-processor macros to enumerate all possible options to work around lack of varidic templates. 最终,所有这些库都使用预处理器宏来枚举所有可能的选项,以解决缺少varidic模板的问题。

How about sidestepping this issue through the use of Boost Bind ? 如何通过使用Boost Bind回避这个问题? You could make your code accept a single argument, or none at all, and bind arguments you need at the call site. 您可以使您的代码接受单个参数,或者根本不接受任何参数,并在调用站点绑定您需要的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM