When does type information flow backwards in C++?

前端 未结 3 1604
栀梦
栀梦 2021-01-29 23:39

I just watched Stephan T. Lavavej talk at CppCon 2018 on \"Class Template Argument Deduction\", where at some point he incidentally says:

In

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-29 23:56

    Stephan T. Lavavej explained the case he was talking about in a tweet:

    The case I was thinking of is where you can take the address of an overloaded/templated function and if it’s being used to initialize a variable of a specific type, that will disambiguate which one you want. (There’s a list of what disambiguates.)

    we can see examples of this from cppreference page on Address of overloaded function, I have excepted a few below:

    int f(int) { return 1; } 
    int f(double) { return 2; }   
    
    void g( int(&f1)(int), int(*f2)(double) ) {}
    
    int main(){
        g(f, f); // selects int f(int) for the 1st argument
                 // and int f(double) for the second
    
         auto foo = []() -> int (*)(int) {
            return f; // selects int f(int)
        }; 
    
        auto p = static_cast(f); // selects int f(int)
    }
    

    Michael Park adds:

    It's not limited to initializing a concrete type, either. It could also infer just from the number of arguments

    and provides this live example:

    void overload(int, int) {}
    void overload(int, int, int) {}
    
    template 
    void f(void (*)(T1, T2), A1&&, A2&&) {}
    
    template 
    void f(void (*)(T1, T2, T3), A1&&, A2&&, A3&&) {}
    
    int main () {
      f(&overload, 1, 2);
    }
    

    which I elaborate a little more here.

提交回复
热议问题