[英]Extracting C Function's Parameters Using C++ Metaprogramming (Example from “Practical C++ Metaprogramming”)
以下是“實用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;
}
抱歉,沒有看過書頁,所以不知道授權在這里是什么意思。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.