【问题标题】:How do I store (adjoint) functors in a pair?如何成对存储(伴随)函子?
【发布时间】:2023-04-03 13:20:01
【问题描述】:

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

它们是这样声明的:

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

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

        }
    };


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

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

        }
    };

这些被一个类用于它的成员变量。

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

附:没有 C++11 或 boost 的解决方案将不胜感激。但我愿意将它们用作最后​​的手段

【问题讨论】:

    标签: c++ functor


    【解决方案1】:

    容器类:

    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);
    

    【讨论】:

    • 如何使用其中的函子?我使用 c.first 和 c.second 吗?
    • @ShayanRC 我扩展了我的答案来解决你的问题。
    • @ShayanRC 您已将operator() 函数定义为采用T&amp;。现在想来,除非改成T const&amp;,否则我写的代码不会编译。
    • @ShayanRC 修复了答案。
    • @ShayanRC 10 只是一个示例值。您必须选择一个更适合您正在执行的操作的值。
    猜你喜欢
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    相关资源
    最近更新 更多