【问题标题】:template for typedef that accepts pointer to both const and non-const functionstypedef 模板,接受指向 const 和非 const 函数的指针
【发布时间】:2017-10-19 08:23:07
【问题描述】:

这是一个类方法的指针,它接受两个整数并返回一个整数:

template <typename T>
using TFunction = int (T::*)(int, int);

我只能在这里传递非常量方法。 如何更改此模板以使其同时接受 const 和非 const 方法?

【问题讨论】:

  • 你的意思是 either const 和非const 函数,对吧?没有单一的指针类型可以同时做到这两点。
  • 我不接受任何会员。它接受T。你的minimal reproducible example 太少了。这是一个 XY 问题。
  • 您不能有一个同时引用两种类型的名称。您可以使用template &lt;typename T&gt; using TCFunction = int (T::*const)(int, int);const 函数命名,或者使用std::function 或您自己的版本键入擦除函数指针。

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


【解决方案1】:

这种情况对于一个条件来说很简单:

template <typename T>
using TFunction = std::conditional_t<
    std::is_const_v<T>,
    int (T::*)(int, int) const,
    int (T::*)(int, int)
>;

现在TFunction&lt;Foo&gt;int (Foo::*)(int, int),而TFunction&lt;Foo const&gt;int (Foo::*)(int, int) const

【讨论】:

  • 但是具有常量成员函数的非 const Foo 类型呢?
  • @Jodocus 这是一个红鲱鱼:我将“const-or-non-const”参数搭载到T,而不是让它成为一个单独的bool .它与您稍后将使用的实际Fooconstness 无关,您仍然可以将TFunction&lt;Foo const&gt; 调用到Foo 上:)
  • 删除了我原来的评论,因为这太棒了。尽管一般T 必须是一个id 表达式(因此一般不能是const T),模板上下文允许同时使用类型信息,保留指向格式良好的成员的指针。
猜你喜欢
  • 2011-03-04
  • 1970-01-01
  • 2014-10-18
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多