【问题标题】:C++ std::function-like template syntaxC++ std::function-like 模板语法
【发布时间】:2015-02-20 15:17:41
【问题描述】:

在 C++11 中,您可以像这样实例化 std::function:

std::function<void(int)> f1;
std::function<int(std::string, std::string)> f2;
//and so on

但是,虽然网络上有大量关于可变参数模板的信息,但我找不到任何关于如何编写可以接受带括号的参数的类似 std::function 的模板的文章。 谁能解释一下语法及其限制,或者至少指出一个现有的解释?

【问题讨论】:

    标签: templates c++11 syntax variadic-templates std-function


    【解决方案1】:

    没什么特别的,就是一个普通的函数类型。当你声明这样的函数时:

    int foo(char a, double b)
    

    那么它的类型是int (char, double)。 “展开”单个参数类型和返回类型的一种方法是使用部分模板特化。基本上,std::function 看起来像这样:

    template <class T>
    struct function; // not defined
    
    template <class R, class... A>
    struct function<R (A...)>
    {
      // definition here
    };
    

    【讨论】:

    • 所以,如果我理解正确的话,int(char, double) 被解释为单个函数类型,但是我们可以通过偏特化提取返回类型和参数列表?
    • @Cynic 是的,这正是它的工作原理。我已经相应地编辑了答案。
    • 我需要像template &lt;typename F&gt; void foo(F(int) intCallable){...}这样的语法:/
    • @MariuszJaskółka 的语法是foo(F intCallable(int))。它就像任何其他函数语法一样:名称位于返回类型和参数列表之间。
    【解决方案2】:

    与任何其他模板非常相似,因为 int(std::string, std::string) 只是一个类型。

    这是一个非常简单的编译示例:

    template <typename FType>
    struct Functor
    {
       Functor(FType* fptr) : fptr(fptr) {}
    
       template <typename ...Args>
       void call(Args... args)
       {
          fptr(args...);
       }
    
    private:
       FType* fptr;
    };
    
    void foo(int x, char y, bool z) {}
    
    int main()
    {
       Functor<void(int, char, bool)> f(&foo);
       f.call(1, 'a', true);
       //f.call(); // error: too few arguments to function
    }
    

    实际上,如果您尝试以兼容的方式调用它,那么我的天真示例已经为您提供了所需的验证,但您可以将 FType 专业化为 ReturnType(ArgTypes...)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多