首页 > 解决方案 > 如何告诉函子模板类用户他必须编写什么函子 operator() 签名?

问题描述

考虑这个使用函子作为模板参数的模板类的无意义示例:(godbolt here

volatile int a = 0;
volatile int b = 0;

template <typename F, typename F2>
class testclass
{
    public:

    bool doOperation(int a)
    {
        F f;
        F2 f2;
        f(a);
        return f2(a);
    }
};

int main()
{
    struct MyFunctor1
    {
        bool operator()(int b)
        {
            a+=b;
            return true;
        }
    };

    struct MyFunctor2
    {
        bool operator()(int b)
        {
            a-=b;
            return false;
        }
    };

    testclass<MyFunctor1, MyFunctor2> instance;
    instance.doOperation(b);
    return 0;
}

让我们考虑testclass用户不知道类的内部结构。所以他不知道他必须为模板参数提供的函子的 operator() 签名。

在这个示例中,我如何告诉用户传递一个其 operator() 签名如下的函子bool (int):以及如何强制编译器检查它?

标签: c++

解决方案


推荐阅读