在使用指向 const 和非 const 方法的成员指针时减少模板专用化的数量

reduce number of template specializations while using member pointer to const and non-const method

本文关键字:const 专用 成员 和非 方法 指针      更新时间:2023-10-16

我有一些模板代码,它接受指向类的共享指针并调用函数或方法。如果被调用的方法定义为const,则会出现问题。

例:

struct Y {}; 
struct X
{
        const Y Go() const { return Y{}; }
        const Y Go2() { return Y{}; }
};
Y f1( std::shared_ptr<X>  ) { return Y{}; }
template< typename FUNC, typename ... ARGS >
auto Do( std::shared_ptr<X>& ptr, FUNC&& f, ARGS&& ... args )
{
    return f( ptr, std::forward<ARGS>(args)... );
}
template < typename CLASS, typename RET, typename ... ARGS>
auto Do( std::shared_ptr<X>& base_ptr, RET (CLASS::*mem_ptr)( ARGS...), ARGS&& ... args )->RET
{
    return (base_ptr.get()->*mem_ptr)( std::forward<ARGS>(args)...);
}
// Any chance to avoid the full duplication of the code here
// to define the member pointer to a const method?
template < typename CLASS, typename RET, typename ... ARGS>
auto Do( std::shared_ptr<X>& base_ptr, RET (CLASS::*mem_ptr)( ARGS...) const, ARGS&& ... args )->RET
{
    return (base_ptr.get()->*mem_ptr)( std::forward<ARGS>(args)...);
}
int main()
{
    auto xptr = std::make_shared<X>();
    Y y1 = Do( xptr, &X::Go );
    Y y2 = Do( xptr, &X::Go2 );
    Y y3 = Do( xptr, &f1 );
}

我的问题是RET (CLASS::*mem_ptr)( ARGS...) const的最后一个专业化.我只想停止复制整个代码,只针对常量。在实际代码中,该函数再次调用另一个模板化代码,这会导致此处重复大量代码。

有机会摆脱常量成员指针的专业化吗?

在 C++17 中,我将使用带有 if constexpr 的单个模板化函数,并检查我是否可以将f作为具有 std::is_invocable 的模板化成员函数调用,然后使用 std::invoke 调用它:

template< typename FUNC, typename ... ARGS >
auto Do( std::shared_ptr<X>& ptr, FUNC&& f, ARGS&& ... args ) {
    if constexpr (std::is_invocable_v<FUNC, decltype(ptr), ARGS...>) {
        return std::invoke(f, ptr, std::forward<ARGS>(args)... );
    }
    else {
        return std::invoke(f, ptr.get(), std::forward<ARGS>(args)... );
    }
}

在 C++17 之前,可以有两个重载:一个用于非成员函数,另一个用于成员函数。然后,您可以使用 SFINAE 根据可调用对象的类型禁用其中一个(使用类似于 std::is_invocable 的内容)。

你可以这样做:

template< typename FUNC, typename ... ARGS >
auto Do( std::shared_ptr<X>& ptr, FUNC&& f, ARGS&& ... args )
-> decltype((f(ptr, std::forward<ARGS>(args)... )))
{
    return f( ptr, std::forward<ARGS>(args)... );
}
template<typename MemberF, typename ... ARGS>
auto Do(std::shared_ptr<X>& base_ptr, MemberF mem_ptr, ARGS&& ... args)
-> decltype((base_ptr.get()->*mem_ptr)( std::forward<ARGS>(args)...))
{
    return (base_ptr.get()->*mem_ptr)( std::forward<ARGS>(args)...);
}

这是一个不需要 SFINAE 的 C++14 版本,它依赖于以下事实:

  • const Y (X::*)()U1 = const Y() U1 X::*相同;
  • connt Y (X::*)() constU2 = const Y() const U2 X::*相同。
template< typename FUNC, typename ... ARGS >
auto Do( std::shared_ptr<X>& ptr, FUNC&& f, ARGS&& ... args )
{
    return f( ptr, std::forward<ARGS>(args)... );
}
template < typename CLASS, typename U, typename ... ARGS>
auto Do( std::shared_ptr<X>& base_ptr, U CLASS::*mem_ptr, ARGS&& ... args )
{
    return (base_ptr.get()->*mem_ptr)( std::forward<ARGS>(args)...);
}

发布不同的答案,因为这与第一个完全不同,而且两者都很有趣(在我看来)。