c++ - 获取静态类函数的类类型

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

我有一个指向静态类函数的函数指针 Foo::bar() ,并想要获取类的类型 ( Foo )。现在,我知道如果 bar 我可以获得类类型是 Foo 的成员函数,而不是静态函数,具有类似以下类型特征的东西:

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

在我看来,编译器知道所有相关信息,那么这是怎么做到的呢?

最佳答案

指向静态成员函数的裸函数指针与指向非成员函数的函数指针属于同一类型

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

#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;
}

关于c++ - 获取静态类函数的类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47619797/

相关文章:

c++ - 怎么理解 "Point of Instantiation"的意思

C++ 元编程 - 在代码中生成错误

c++ - 在 C++ 中结合 getter 函数使用重载的比较运算符>

c++ - 从 python IDLE 问题调用 c++

c++ - 类元组类型(元组、对)的模板重载

c++ - 没有匹配函数调用 ‘std::less<int>::less(const int&, const int&)’

c++ - 在模板化函数中将 std::vector 设置为本地会导致编译失败

C++11:根据项目计数在 std::array 和 std::unordered_map 之间实现一个选择器

c++ - 在 Structure from Motion 中进行三角剖分后

c++ - 无法在 boost spirit 中指定 skipper (编译器错误)