C++ - const 与非 const 成员函数 - 带有函数指针的模板

Mar*_*rry 5 c++ templates pointers variadic-templates c++11

我有一个代码,大量使用模板。一个例子是这样的:

template <class MT>
struct class_method_info;

template <class T, class Res, class... Args>
struct class_method_info<Res(T::*)(Args...)>
{
    typedef std::tuple<Args&&...> ArgsTuple;
    typedef T ClassType;
    typedef Res RetVal;
    static constexpr std::size_t ArgsCount = sizeof...(Args);
    static constexpr bool IsClassMethod = true;     
};
Run Code Online (Sandbox Code Playgroud)

这适用于非常量成员函数指针。

如果我更改Res(T::*)(Args...)Res(T::*)(Args...) const,我可以传递const函数指针。然而,即使这是一个解决方案,它也会弄乱我的代码,因为现在我的所有东西都加倍了,而且有很多这样的东西。

还有其他办法吗?

krz*_*zaq 4

您可以添加 的专门化const this,它将继承另一个的大部分实现:

template <class MT>
struct class_method_info;

template <class T, class Res, class... Args>
struct class_method_info<Res(T::*)(Args...)>
{
    typedef std::tuple<Args&&...> ArgsTuple;
    typedef T ClassType;
    typedef Res RetVal;
    static constexpr std::size_t ArgsCount = sizeof...(Args);
    static constexpr bool IsClassMethod = true;
    static constexpr bool IsConstThis = false;
};


template <class T, class Res, class... Args>
struct class_method_info<Res(T::*)(Args...) const> : class_method_info<Res(T::*)(Args...)>
{
    static constexpr bool IsConstThis = true;
};
Run Code Online (Sandbox Code Playgroud)

演示