如何在一对中存储(伴随)仿函数?

时间:2014-04-25 03:03:33

标签: c++ functor

我有两个伴随的仿函数,即它们成对出现 如果一个是doX(),则另一个是undoX()

他们被宣布为如此:

    template< typename T >
    struct doSomething{
        void operator()( T &x ) const {

        .....
        .....
        .....

        }
    };


    template< typename T >
    struct undoSomething{
        void operator()( T &x ) const {

        .....
        .....
        .....

        }
    };

这些由类的成员变量使用。

如何将它们存储在std :: pair中,我可以在类的构造函数中传递它?

P.S。没有C ++ 11或boost的解决方案将不胜感激。但我愿意将它们作为最后的手段使用

1 个答案:

答案 0 :(得分:2)

容器类:

struct Container
{
   typedef int DoUndoType; // This is an example, the actual type will
                           // have to be decided by you.

   // The constructor and its argument.
   Container(std::pair<doSomething<DoUndoType>,
                       undoSomething<DoUndoType>> const& doUndoPair) : doUndoPair(doUndoPair) {}

   std::pair<doSomething<DoUndoType>,
             undoSomething<DoUndoType> doUndoPair;
};

使用Container类:

// Construct an object.
Container c(std::make_pair(doSomething<Container::DoUndoType>(),
                           unDoSOmething<Container::DoUndoType>()));

// Use the pair.
int arg = 10;
c.doUndoPair.first(arg);
c.doUndoPair.second(arg);