【问题标题】:C++ - const vs non const member function - template with function pointersC ++ - Const VS非Const成员函数 - 具有功能指针的模板
【发布时间】:2017-03-19 03:08:54
【问题描述】:

我有一个代码,它正在使用模板。一个例子是这样的:

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

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

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

还有其他方法吗?

【问题讨论】:

  • 您是否考虑过使用实现创建模板化父类并在那里传递所有必需的模板参数?
  • 我不知道你的用例是什么,但我希望std::mem_fn 没有满足你的要求,否则你应该看看。

标签: c++ c++11 templates pointers variadic-templates


【解决方案1】:

您可以为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;
};

demo

【讨论】:

    猜你喜欢
    • 2016-08-17
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    相关资源
    最近更新 更多