【发布时间】:2019-11-22 06:36:27
【问题描述】:
#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