c++ - 使用 C++ 元编程提取 C 函数的参数(来自 "Practical C++ Metaprogramming"的示例)

标签 c++ metaprogramming template-meta-programming

以下是“实用 C++ 元编程”(第 16/17 页)中的示例:

#include <tuple>
#include <typeinfo>

template <typename F>
struct make_tuple_of_params;

template <typename Ret, typename... Args>
struct make_tuple_of_params<Ret (Args...)>
{
   using type = std::tuple<Args...>;
};

template <typename F>
using make_tuple_of_params_t = typename make_tuple_of_params<F>::type;

template<typename F>
void some_magic_function(F f)
{
   // if F is in the form void(double*, double*)
   // make_tuple_of_params is std::tuple<double*, double*>
   make_tuple_of_params_t<F> params;

   // ...
}

void Foo(double* x, double* y) { }

int main()
{
   some_magic_function(Foo);
}

编译失败:

$ clang++ -std=c++14 MakeTuple.cpp
MakeTuple.cpp:14:5: error: implicit instantiation of undefined template 'make_tuple_of_params<void (*)(double *, double*)>'

这是不是因为make_tuple_of_params的非特化版本(上面代码的第4行和第5行)没有定义?

最佳答案

您实际上需要不同的重载,具体取决于您是从指针还是从签名模板参数中提取它,请参见下文。

template <typename F>
struct make_tuple_of_params;

template <typename Ret, typename... Args>
struct make_tuple_of_params<Ret (*)(Args...)> {
  using type = std::tuple<Args...>;
};

template <typename Ret, typename... Args>
struct make_tuple_of_params<Ret(Args...)> {
  using type = std::tuple<Args...>;
};

template <typename F>
using make_tuple_of_params_t = typename make_tuple_of_params<F>::type;

template <typename F>
bool some_magic_function(F f) {
  // if F is in the form void(double*, double*)
  // make_tuple_of_params is std::tuple<double*, double*>
  return std::is_same<std::tuple<double*, double*>, make_tuple_of_params_t<F>>::value;
}

void Foo(double* x, double* y) {}

int main() {
  cerr << some_magic_function(Foo) << endl;
  cerr
    << std::is_same<std::tuple<int, int>, make_tuple_of_params_t<void(int, int)>>::value
    << endl;
  // The latter one might be handy in some of template metaprogramming constructs
  return 0;
}

不好意思,没看过书页,不知道作者的意思。

关于c++ - 使用 C++ 元编程提取 C 函数的参数(来自 "Practical C++ Metaprogramming"的示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44395240/

相关文章:

Ruby eigenclass(单例类)创建了吗?为了哪个?

c++ - SFINAE 使基础模板总是导致错误

c++ - 模板类中的命名空间特化

c++ - 控制用户界面的最佳方式

c++ - 什么是 internal::state::Entry 以及它在 mesos 中定义的位置

c++ - 如何使用 C++ 11 创建计时器事件?

c++ - 奇怪的图案 : all functions/methods return error-code using the same type in C++

c++ - 两个类型列表是否可以在恒定时间内拼接?

c++ - 为什么这个嵌套的 lambda 不被认为是 constexpr?

c++ - Variadic 模板元编程 : a bug in clang++ or g++?