如何设置模板参数以允许灵活选择不同类型的函数

How to set the template parameter to allow flexibility in choosing different kinds of functions

本文关键字:选择 许灵活 同类型 函数 参数 何设置 设置      更新时间:2023-10-16

例如

template<class D, Function>
struct A
{
    void foo()
    {
        D d;
        int i = Function(d);
        // Here function can be a free function: int fun(D& d)
        // or member function: int D::fun()
        // or function object:
    }
};

如何设置模板参数以允许在选择不同类型的函数时具有灵活性?代码可以更改,只允许灵活性很好。感谢

最好将函数传递到类中。如果你不传递一些对象,你就必须去构造这样一个对象来调用:

template<class D, typename Function>
struct A
{
    explicit A(Function f) : func_(f) { }
    void foo()
    {
        D d;
        int i = func_(d);
        // Here function can be a free function: int fun(D& d)
        // or member function: int D::fun()
        // or function object:
    }
    Function func_;
};

由于可调用类型几乎总是无状态的或具有微小的内部状态,因此复制这些类型不应该有任何影响。