【问题标题】:Cannot get pointer to member funtion out of decltype无法从 decltype 中获取指向成员函数的指针
【发布时间】:2020-10-06 23:42:12
【问题描述】:

我观察到我无法使用类实例 c 执行 &decltype(c)::f 获取指向成员函数 f 的指针,但我可以使用类类型执行 &C::f 获取指向成员函数的指针C,我认为和decltype(c)是一样的。

看这个最小的例子:

struct C{
    int f()
    {
        return 5;
    }
} c;

template<typename T, T t, typename S, S*s> void callCf()
{
    (s->*t)();
}

int main()
{
  callCf<decltype(&decltype(c)::f),&decltype(c)::f,C,&c>();
}

编译得到:

In function 'int main()':
15:3: error: parse error in template argument list
15:58: error: no matching function for call to 'callCf()'
15:58: note: candidate is:
8:49: note: template<class T, T t, class S, S* s> void callCf()
8:49: note:   template argument deduction/substitution failed:
15:58: error: template argument 2 is invalid

按预期使用以下工作:

int main()
{
  callCf<decltype(&decltype(c)::f),&C::f,C,&c>();
}

即使这样也有效:

int main()
{
  using tC = decltype(c);
  callCf<decltype(&decltype(c)::f),&tC::f,C,&c>();
}

这也有效:

template<typename T>
struct forward_type{
    typedef T type;
};

int main()
{
  callCf<decltype(&decltype(c)::f),&forward_type<decltype(c)>::type::f,C,&c>();
}

我的问题是:为什么不能使用 decltype 来获取指向成员函数的指针 &amp;decltype(c)::f?

编辑:@Paul Sanders 在 cmets 中表明最小示例适用于 c++17。我仍在使用c++14。 c++17 是否包含对允许我的最小示例编译的语言的一些更改?

【问题讨论】:

  • 您使用的是什么编译器和版本?这个works给我。
  • 我看到它适用于c++17。我正在使用c++14,也是 gcc 6.1.0
  • 你能把你的编译器标志改成C++17吗?不知道为什么需要这样做,我不是标准专家。
  • @PaulSanders 嗯,这绝对是一个解决方案......虽然它涉及将大量代码移动到新标准,这目前不是很方便。

标签: c++ templates c++14 pointer-to-member-functions


【解决方案1】:

c 是一个左值,所以decltype(c) 本身不会返回C 类型,这就是decltype(c)::f 不起作用的原因。 decltype(c) 实际上会返回 C&amp; 引用类型:

  1. 如果参数是T 类型的任何其他表达式,并且
    ...
    b) 如果expression 的值类别是lvalue,那么decltype 产生T&amp;;
    ...

您可以使用std::remove_reference/_t 从C&amp; 中获取C 类型,例如:

int main()
{
    callCf<
        decltype(&std::remove_reference_t<decltype(c)>::f),
        &std::remove_reference_t<decltype(c)>::f,
        std::remove_reference_t<decltype(c)>,
        &c
    >();
}

Live Demo

然后可以使用using 语句来简化:

int main()
{
    using tC = std::remove_reference_t<decltype(c)>;
    callCf<decltype(&tC::f), &tC::f, tC, &c>();
}

Live Demo

【讨论】:

  • 不错。即使callCf&lt;decltype(&amp;C::f),&amp;std::remove_reference&lt;decltype(c)&gt;::type::f,C,&amp;c&gt;(); 直接在没有using 的情况下工作。我现在的问题是为什么callCf&lt;decltype(&amp;decltype(c)::f),&amp;decltype(c)::f,C,&amp;c&gt;(); 在c++17 中工作?
  • 如果你对using 指令没问题,那么using tC = decltype(c); 已经在c++14 中工作了。我不知道它为什么会起作用。
  • 我意识到你不需要std::remove_reference,你只需要通过不同的模板转发类型,比如template&lt;typename T&gt;struct forward_type{ typedef T type; };
  • 如果我定义一个函数C fun_ret_C(){return C();} 以便它返回一个右值C 实例,&amp;decltype(fun_ret_C())::f 仍然在callCf&lt;decltype(&amp;C::f),&amp;decltype(fun_ret_C())::f,C,&amp;c&gt;(); 中给出错误,所以在我看来问题不在于右值或右值。还有错误是parse error in template argument list,很可疑……
猜你喜欢
  • 1970-01-01
  • 2012-02-10
  • 2022-12-01
  • 2016-12-27
  • 2023-03-23
  • 2020-12-11
  • 2021-12-22
  • 1970-01-01
相关资源
最近更新 更多