【问题标题】:Typedef for a pointer to a cv- and/or ref-qualified member function指向 cv 和/或 ref 限定成员函数的指针的 typedef
【发布时间】:2016-03-17 20:32:54
【问题描述】:
struct foo {
    void bar(int&&) && { }
};

template<class T>
using bar_t = void (std::decay_t<T>::*)(int&&) /* add && if T is an rvalue reference */;

int main()
{
    using other_t = void (foo::*)(int&&) &&;
    static_assert(std::is_same<bar_t<foo&&>, other_t>::value, "not the same");

    return 0;
}

我想要那个

  • bar_t&lt;T&gt; 产生 void (foo::*)(int&amp;&amp;) 如果 T = foo
  • bar_t&lt;T&gt; 产生 void (foo::*)(int&amp;&amp;) const 如果 T = foo const
  • bar_t&lt;T&gt; 产生 void (foo::*)(int&amp;&amp;) &amp; 如果 T = foo&amp;
  • bar_t&lt;T&gt; 产生 void (foo::*)(int&amp;&amp;) const&amp; 如果 T = foo const&amp;

等等。我怎样才能做到这一点?

【问题讨论】:

  • 这个的用例是什么?
  • 分配 CV 限定符的方式与您可以通过完美转发分配左值/右值的方式相同。假设 CV 和 LR 不变性通常是不正确的,但提供它确实很有价值,特别是如果它是您可以定义为特征的属性。您不必为每个变体编写单独的逻辑 - 因此是“不变性” - 您将能够归纳推理这些变体的组合。

标签: c++ templates function-pointers c++14 member-function-pointers


【解决方案1】:

这应该可以完成工作:

template <typename, typename T> struct add {using type = T;};
template <typename F, typename C, typename R, typename... Args>
struct add<F const, R (C::*)(Args...)> {using type = R (C::*)(Args...) const;};

template <typename F, typename C, typename R, typename... Args>
struct add<F&, R (C::*)(Args...)> :
  std::conditional<std::is_const<F>{}, R (C::*)(Args...) const&,
                                       R (C::*)(Args...) &> {};
template <typename F, typename C, typename R, typename... Args>
struct add<F&&, R (C::*)(Args...)> :
  std::conditional<std::is_const<F>{}, R (C::*)(Args...) const&&,
                                       R (C::*)(Args...) &&> {};

Demo。请注意,F 的基础类型将被忽略。

【讨论】:

  • ...需要...更多...部分...专业化... ;)
  • @T.C. “应该”。我不会在晚上 11 点讨论指向可变成员函数的指针。 ;)
  • en.cppreference.com/w/cpp/types/is_function > “可能的实现”显示了这会变得多么丑陋。另一方面,合格的限定词和主题是正交的,相应的std::add_const 可以自动执行您已经手动执行的操作。在未来证明我们反对 C++23 的“16777215 规则”可能是值得的。 :)
猜你喜欢
  • 2011-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多