Cannot inititialize std::function implicitly

后端 未结 2 2073
悲哀的现实
悲哀的现实 2021-01-14 18:42

I\'ve written this functor to perform an and operation (&&):

// unary functor; performs \'&&\'
template 
         


        
2条回答
  •  青春惊慌失措
    2021-01-14 19:17

    The problem is that there's no way to deduce T in this context. Let's look at it from the compiler's perspective:

    template 
    AND And(function xx, function yy)
    
    // Later, invoked as:
    And( is_odd, is_big )
    

    "Hm, no T is specified on the call, I will have to deduce it. What's the argument? is_odd, which is decayed to type int (*)(int). Now, I would have to instantiate std::function for all possible T values and see for which/if any it can be constructed from type int (*)(int). Well, there's infinitely many of them. Not gonna do this."

    It would work if you specified the T tempalte argument explicitly:

    return any_of( first, last, And( is_odd, is_big ) );
    

    Live example


    Note that this holds even if you changed is_odd and is_big to match the function signature exactly (returning bool and taking const int&). It's the deduction that's the problem.

提交回复
热议问题