c++ - 模板函数返回模板函数指针

标签 c++ templates boost overloading metaprogramming

目前我实现了两个模板函数,每个都返回一个使用 boost::variant 包装的模板函数指针:

  1. 函数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>;
        }
    }
    
  2. 函数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

Atemplate<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 .普通类型,如 intA_T<A>可以用作变量类型的种类 * .

撇开理论不谈,您可以拥有这样的模板模板参数是相当直观的,即使语法一开始看起来很奇怪。

关于c++ - 模板函数返回模板函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46596338/

相关文章:

c++ 编译器将模板语法视为 '<' 运算符

使用 Boost Thread 的 C++ 链接器错误

c++ - 文件映射对象和文件对象可以互换使用吗?

可访问 C++ 私有(private)成员?

templates - 如何覆盖 MATLAB 中的默认文本

c++ - 嵌套类模板问题

c++ - 为什么 boost 可选引用不是 T* 的包装器?

c++ - ptr_vector - _CrtDumpMemoryLeaks() - 即使调用析构函数也会发生内存泄漏

c++ - 使用 ifstream 从文本文件中读取

c++ - DX11 OpenGL 互操作 : can't copy buffer