Reputation: 1434
I defined following functions for string processing:
void sub(const std::string & repl){
}
void sub(std::function<std::string()> userfun){
}
When I call with an anonymous function, it is OK
sub([=](){return "a"; });
But when I call with string, it has failed
sub("a");
error C2668: 'sub' : ambiguous call to overloaded function
Is it possible to avoid ambiguous call when calling with a string against anonymous function parameter
Using Visual C++ 2013
UPDATE2
Create a new console project and put everyting from sketch and still failed in VC++2013
// overload.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string>
#include <functional>
void sub(const std::string & repl) {
}
void sub(std::function<std::string()> userfun) {
}
int _tmain(int argc, _TCHAR* argv[])
{
sub("a");
return 0;
}
1>------ Build started: Project: overload, Configuration: Debug Win32 ------
1>Build started 2016-06-22 17:55:00.
1>InitializeBuildStatus:
1> Touching "Debug\overload.tlog\unsuccessfulbuild".
1>ClCompile:
1> overload.cpp
1>c:\users\xxxxxx\documents\visual studio 2013\projects\overload\overload\overload.cpp(15): error C2668: 'sub' : ambiguous call to overloaded function
1> c:\users\xxxxxx\documents\visual studio 2013\projects\overload\overload\overload.cpp(10): could be 'void sub(std::function<std::string (void)>)'
1> c:\users\xxxxxx\documents\visual studio 2013\projects\overload\overload\overload.cpp(7): or 'void sub(const std::string &)'
1> while trying to match the argument list '(const char [2])'
1>
1>Build FAILED.
1>
UPDATE:
My VS about information:
Upvotes: 1
Views: 246
Reputation: 234825
It's a compiler bug: sub(std::string("a"));
is an adequate workaround. (Binding an anonymous temporary to a const
reference is legal in C++.)
MSVC2013 compiles the statement
std::function<std::string()> foo("a");
Showing that "a"
is a valid constructor argument for that type. (It appears to be using, in error, the constructor function( std::nullptr_t )
).
Reference: http://en.cppreference.com/w/cpp/utility/functional/function/function
Upvotes: 3