目前我实现了两个模板函数,每个都返回一个使用 boost::variant 包装的模板函数指针:
函数fa
typedef boost::variant<&A<int>,&A<double>> A_T; A_T fa(string type) { switch(type){ case "int": return &A<int>; case "double": return &A<double>; default: return &A<int>; } }
函数fb
typedef boost::variant<&B<int>,&B<double>> B_T; B_T fb(string type) { switch(type){ case "int": return &B<int>; case "double": return &B<double>; default: return &B<int>; } }
我的问题是“我们能否将这两个函数合并为一个以 A 或 B 的仿函数指针作为模板参数的模板函数?”。我需要这个的原因是因为我可能有两个以上的仿函数,比如 A 和 B。
最佳答案
简单:
template<template<typename> class F> // template template
using F_T = boost::variant<F<int>&, F<double>&>; // Need C++11 for this (not strictly needed) alias
template<template<typename> class F>
F_T<F> f(std::string type) {
if(type == "double") return something<F<double>&>();
else return something<F<int>&>();
}
using A_T = F_T<A>;
A_T at = f<A>("int");
// F_T<int> broken; // invalid: int is not a template<typename> class
// f<int>("int") // invalid: int is not a template<typename> class
A
是template<typename> class
, 所以它可能是 F_T
的类型参数和 f
, 它们都是 template<template<typename> class>
.比较有功能a => b
并将其作为参数传递给函数 (a => b) => c
.我们说一个函数 [](int i) { return i + 5; }
有类型 int => int
, 就像一个类型 template<typename> class A
有种类 * -> *
(具体类型到具体类型)。就像高阶函数可以有类似 (A => A) => A
的类型一样, 更高种类的类型可以有类似 (* -> *) -> *
的种类,例如F_T
.普通类型,如 int
和 A_T<A>
可以用作变量类型的种类 *
.
撇开理论不谈,您可以拥有这样的模板模板参数是相当直观的,即使语法一开始看起来很奇怪。
关于c++ - 模板函数返回模板函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46596338/