简体   繁体   English

std :: tuple到成员函数

[英]std::tuple to member functions

I'm still trying to get the swing of metaprogramming, and I'm stumped. 我仍然试图摆脱元编程,我很难过。

What's I'd like to do is create a class/struct/whatever, supply it a std::tuple and have it automatically generate member functions based on the object types in the tuple. 我想做的是创建一个类/ struct / whatever,为它提供一个std :: tuple并让它根据元组中的对象类型自动生成成员函数。 The goal is to have classes derive from MessageHandler 目标是让类派生自MessageHandler

eg 例如

typedef std::tuple< MessageA, MessageB, MessageC > MessageSet;

template< class T >
class MessageHandler
{
  // some magic metaprogramming would "create"...
  virtual void processMsg( const MessageA& ) = 0;
  virtual void processMsg( const MessageB& ) = 0;
  virtual void processMsg( const MessageC& ) = 0;
};

I've read that you can't have virtual functions in templates, but I didn't know if that was still true for C++11. 我已经读过你不能在模板中使用虚函数,但我不知道C ++ 11是否仍然如此。

Thanks. 谢谢。

The answer is variadic template, partial specialization, and inheritance as: 答案是可变参数模板,部分特化和继承:

//primary template!
template<typename T>
class MessageHandler;

//variadic template, partial specialization and inheritance!
template<typename H, typename ...T>
class MessageHandler<std::tuple<H,T...>>  : public MessageHandler<std::tuple<T...>>
{
    virtual void processMsg( const H& ) = 0;
};

template<typename T>
class MessageHandler<std::tuple<T>>
{
    virtual void processMsg( const T& ) = 0;
};

You don't need tuple to do that: 你不需要元组来做到这一点:

struct MessageA{};struct MessageB{};struct MessageC{};

template <typename T>
struct message_interface {
  virtual void processMessage(const T& t) = 0;
};

template< typename... Args >
struct message_handler : public message_interface<Args>...
{};

struct message_impl : message_handler<MessageA, MessageB, MessageC>
{
  void processMessage(const MessageA&){}
  void processMessage(const MessageB&){}
  void processMessage(const MessageC&){}
};

int main()
{
  message_impl i;
  return 0;
}

It would probably be a good idea to check if the argument list is unique and static assert on that. 检查参数列表是否唯一且静态断言可能是个好主意。 Also make sure it does not contain reference types or other undesirables. 还要确保它不包含引用类型或其他不受欢迎的类型。 Those will usually end up as errors when you try to form the argument type but it will safe your users some trouble. 当您尝试形成参数类型时,这些通常会以错误结束,但它会为您的用户带来一些麻烦。

EDIT: If you absolutely require to support tuple add a specialization: 编辑:如果你绝对需要支持tuple添加专业化:

template< typename... Args >
struct message_handler< std::tuple<Args...> > : public message_interface<Args>...
{};

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

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