如何在调用时减少模板参数的数量

How to make number of template parameters less in calling?

本文关键字:参数 调用      更新时间:2023-10-16

我有一个成员函数指针作为模板参数的模板函数

template<
    class Object,
    class Property,
    void (Object::*setProperty)(Property const&)
>
void f(Object& object, Property const& property)

每次,我都必须用3个模板参数调用函数,如下所示

f<A, Value, &A::setValue>(a, value);

使用模板参数派生或其他技术使模板参数数量减少的任何方法

f<&A::setValue>(a, value)

我的第一个想法是"不",但后来我意识到有一种奇怪的方式:

template<class Object, class Property>
struct APointlessName { //needs a better name, but I can't think of one right away
    APointlessName(Object& object, Property const& property)
    :object(&object), property(&property)
    {}
    template<void (Object::*setProperty)(Property const&)>
    void with() 
    {
        Object& object = *(this->object);
        Property const& property= *(this->property);
        //your function code goes here
    }
    Object* object;
    Property const* property;
};
template< class Object, class Property>
APointlessName<Object,Property> f(Object& object, Property const& property)
{return APointlessName<Object,Property>(object, property);}

,然后这样使用:

f(a, value).with<&A::setValue>();

确实有点奇怪,但它确实避免了显式类型。希望有人能想出更好的办法。