我有一些模板代码,它采用指向类的共享指针并调用函数或方法。问题来了,如果被调用的方法被定义为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
. 我只是想停止为 const 复制整个代码。在现实世界的代码中,该函数再次调用另一个模板化的函数,这导致此处重复了大量代码。
有没有机会摆脱 const 成员指针的特化?