带有const限定符的自由函数类型的c++专门化

C++ specialization with free functions types with const-qualififier

本文关键字:函数 类型 c++ 专门化 自由 带有 const      更新时间:2023-10-16

不可能使自由函数具有const- qualified,但是下面的专门化是什么意思,什么时候应用?

template<typename _Res, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res(_ArgTypes...) const>
{ typedef _Res result_type; };

我可以这样使用这个专门化:

typedef _Weak_result_type_impl<int () const>::result_type type;

但是函数类型是"int () const"。什么时候使用?

这个const可以用来捕获const成员函数(正如0x499602D2所指出的)。

考虑下面的例子:

#include <iostream>
using namespace std;
class foo
{
    public:
     void bar1() { cout << "bar1n"; }
     void bar2() const { cout << "bar2n"; }
};
template <typename T, void (T::*mf)() const>
struct Test
{
   void call(T & obj) { (obj.*mf)(); }
};
int main()
{
  foo f;
  //Test<foo, &foo::bar1> t; // Doesn't compile
  //t.call(f);
  Test<foo, &foo::bar2> t2;
  t2.call(f);
  return 0;
}

模板Test只能捕获const成员函数(否则不能编译)。您可以很容易地想象基于成员函数的连续性的专门化,这可能是您的代码正在做的(如果没有更多的上下文就无法判断)


现场演示