【问题标题】:Parentheses inside template arguments e.g. std::function<int(int, float)>模板参数中的括号,例如std::function<int(int, float)>
【发布时间】:2021-04-19 09:36:39
【问题描述】:

我在第 3 部分中阅读了有关 std::function 的这个(长)答案,关于 C++ 中的回调 https://stackoverflow.com/a/28689902/3832877,它演示了使用在括号中具有其他类型的模板参数。我的意思的例子:

std::function<int(int, float)> foo; //for a function returning int with one int and one float argument
std::function<int(C const &, int)> moo; //from the above thread, for member function of class C taking one int argument and returning int

我了解std::function 中定义函数签名的用法,但我不明白编译器如何解析这些模板参数。括号中的类型对编译器意味着什么?此语法是否还有其他用途,还是专门为std::function 和相关的 STL 类创建的?我可以编写自己的使用这种语法的类吗?

【问题讨论】:

    标签: c++ templates c++17 std-function


    【解决方案1】:

    这些是函数的类型。 int(int,int) 是一个函数类型,它接受两个 int 参数并返回一个 int

    为了演示,请考虑以下示例:

    #include <type_traits>
    #include <iostream>
    
    int foo(int,int){ return 42;}
    
    int main(){
        std::cout << std::is_same< decltype(foo), int(int,int)>::value;
    }
    

    它将foo的类型与int(int,int)的类型进行比较,结果确实是1

    参见此处:https://en.cppreference.com/w/cpp/language/function

    被声明函数的类型由返回类型(由声明语法的decl-specifier-seq提供)和函数声明符组成

    noptr-declarator ( parameter-list ) cv(optional) ref(optional) except(optional) attr(optional)    (1)     
    noptr-declarator ( parameter-list ) cv(optional) ref(optional) except(optional) attr(optional) -> trailing    (2)     (since C++11)
    

    我可以编写自己的使用这种语法的类吗?

    是的,你可以。简而言之,int(int,int) 和其他类型一样:

    #include <iostream>
    
    template <typename T>
    void foo(T t){
        t(42);
    }
    
    void bar(int x) { std::cout << x; }
    
    int main() {
       foo< void(int) >(bar);
       // ... or ...
       using fun_type = void(int);
       foo< fun_type >(bar);
    }
    

    【讨论】:

    • 这并没有真正解释所涉及的语法,因为如果您声明一个指向函数的指针,那么您必须使用returntype(*ptr)(arguments) 那么编译器如何按照 OP 的描述解析这种语法?
    • @Devolus 我不明白这个问题是询问解析的细节。 OP 在问“括号中的类型对编译器意味着什么?”和“这种语法还有其他用途,还是专门为 std::function 和相关的 STL 类创建的?”我认为我的回答既能解决问题,又能解决
    • @Devolus 也许我最后的编辑是你所缺少的。
    • @Devolus 它是一个和其他类型一样的类型,但我可以回答它是否特定于std::function 我也有一个没有std::function 的例子。无论如何,我会添加另一个
    • 啊!所以int(int, int) 只是“另一种”任意类型(即使它看起来很奇怪)。我不清楚。也许您应该将foo with int(int,int) 更改为foo with type int(int,int),这将使IMO 更清晰。
    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    相关资源
    最近更新 更多