C++ - 常量成员函数 vs 非常量成员函数 - 使用函数指针的模板

5

我有一段代码,其中大量使用了模板。一个例子如下:

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;     
};

这适用于非const成员函数指针。 如果我将Res(T::*)(Args...)更改为Res(T::*)(Args...) const,我可以传递const函数指针。然而,即使这是一种有效的解决方案,它也会破坏我的代码,因为现在我的所有内容都是成双成对的,并且有很多这样的情况。 是否有其他方法?

你是否考虑过创建带有实现的模板父类,并在那里传递所有必需的模板参数? - W.F.
我不知道你的使用情况是什么,但我希望 std::mem_fn 没有满足你的要求,否则你应该看一下它。 - Arunmu
1个回答

4
您可以为constthis添加一个专门的特化版本,它将继承大部分实现方式从另一个版本中继承:
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;
};

demo


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接