非捕获lambda和函数指针作为函数重载时的模糊性参数

问题描述 投票:1回答:1
#include <functional>
#include <iostream>

template<typename T>
void test( std::function< void ( const T& ) > f )
{
    T val {};
    f( val );

    std::cout << "std::function" << std::endl;
}

template<typename T>
void test( void(*f) ( const T& ) )
{
    T val {};
    f( val );

    std::cout << "function pointer" << std::endl;
}

int main()
{
    auto capturing_var { 0 };

    // Works because implicit conversion to function pointer isn't applied when lambda is capturing
    test< int >( [ capturing_var ]( const int& x ) { } );

    // Doesn't work because implicitly convertible to function pointer and makes ambiguity
    // I want this line to work somehow, how can i make it worked with same client code ? Is it possible ?
    test< int >( []( const int& x ) { } );

    // This line is finer if it works, but in this case compiler cannot deduce T and also ambiguous if it could
    test( []( const int& x ) { } );

    // Works because of unary + operator so conversion to function ptr and i dont need to specify T
    test( +[]( const int& x ) { } );

    return 0;
}

实际上,我只是希望该代码能够在不更改main()中的任何内容的情况下工作,但是我不确定是否可能。

我可以省略使用函数指针的重载函数,然后它可以工作,但是在那种情况下,我需要指定T是什么。

注意:我需要推导T

c++ function-pointers std-function overload-resolution
1个回答
0
投票

您可以使用this question中描述的技术进行一些小的后处理。

最小示例:

template<typename Ret, typename Arg>
Arg argument_type(Ret(*)(Arg));

template<typename Ret, typename Fn, typename Arg>
Arg argument_type(Ret(Fn::*)(Arg) const);

template <typename Fn>
auto argument_type(Fn) -> decltype(argument_type(&Fn::operator()));

template<typename T = void, typename Fn>
void test(Fn fn) {
    using S = std::conditional_t<std::is_void_v<T>, 
        std::decay_t<decltype(argument_type(fn))>, T>;

    std::cout << "S = " << boost::typeindex::type_id_with_cvr<S>().pretty_name() 
              << std::endl;
}

int main() {
    int capturing_var;

    test<int>([capturing_var](const int& x) {}); // S = int
    test<int>([](const int& x) {});              // S = int
    test([](const int& x) {});                   // S = int 
    test(+[](const int& x) {});                  // S = int
}
© www.soinside.com 2019 - 2024. All rights reserved.