如何告诉函子模板类用户他必须编写什么函子operator()签名?

2024-01-30

考虑这个使用函子作为模板参数的模板化类的毫无意义的示例:(godbolthere https://godbolt.org/z/TdeGh7)

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)? 我怎样才能强制编译器检查它?


None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何告诉函子模板类用户他必须编写什么函子operator()签名? 的相关文章

随机推荐