获取静态类函数的类类型

时间:2017-12-03 15:15:32

标签: c++ templates metaprogramming template-meta-programming

我有一个指向静态类函数Foo::bar()的函数指针,并希望得到类的类型(Foo)。现在,我知道如果barFoo的成员函数,而不是静态函数,我可以得到类类型,类似于以下类型特征:

template<class T> struct class_of; template<class T, class R> struct class_of<R T::*> { using type = T; };

但是,这对静态功能不起作用。我想做的是以下内容: class_of<Foo::bar>::type == Foo

在我看来,编译器知道所有相关信息,那么如何做呢?

1 个答案:

答案 0 :(得分:1)

指向静态成员函数的裸函数指针是与相同类型的 ,作为指向非成员函数的函数指针。

也许您可以在函数指针周围使用包装器来包含类信息:

#include <iostream>

struct Foo {
  template<class Arg>
  static void bar(Arg arg) {
    std::cout << "called with " << arg << std::endl;
  }
};

template<class T, class Ret, class... Args>
struct Wrapper {
  using F = Ret(*)(Args...);

  F f_;

  constexpr Wrapper(F f) noexcept : f_{f} {}

  template<class... RealArgs>
  constexpr Ret operator()(RealArgs&&... args) const {
    return f_(std::forward<RealArgs>(args)...);
  }
};

template<class T, class Ret, class... Args>
constexpr Wrapper<T, Ret, Args...> make_wrapper(Ret(*f)(Args...)) {
  return Wrapper<T, Ret, Args...>(f);
}

template<class T>
void inspect(const T&) {
  std::cout << __PRETTY_FUNCTION__ << std::endl;
}

int main() {
  constexpr auto foobar_int = make_wrapper<Foo>(Foo::bar<int>);
  inspect(foobar_int);
  foobar_int(4);

  constexpr auto foobar_double = make_wrapper<Foo>(Foo::bar<double>);
  inspect(foobar_double);
  foobar_double(3.8);

  return 0;
}
相关问题