声明具有给定模板参数功能的相同签名的函数

时间:2013-09-05 19:02:35

标签: c++ templates c++11 crtp

我正在编写一个要派生的包装类,它隐藏了实现。如何获取给定模板参数功能的签名?

template <class T>
struct wrapper
{
  static typename std::result_of<&T::impl>::type
  call(...) { // this function has the same signature of T::impl();
    // here goes the jobs to do, such as logging or something
    return T::impl(...);
  }
};

struct sum : public wrapper<sum>
{
private:
  friend class wrapper<func>
  static int impl(int a, int b, int c) {
    return a + b + c;
  }
};

int main()
{
  bind_to(&sum::call); // set binding
  std::cout << sum::call(1,2,3) << std::endl;
}

1 个答案:

答案 0 :(得分:1)

使用参数包:

template <class T>
struct wrapper
{
    template <typename... Args>
    auto call(Args&&... args) -> decltype(T::impl(std::forward<Args>(args)...))
    {
        return T::impl(std::forward<Args>(args)...);
    }
};