问题
I have been using a simple char buffer class for a number of years under Visual Studio 2005 and 2008. I converted to VS 2013 today and I am getting ambiguous conversion errors in different scenarios. I have removed unneeded portions of the code:
#include <string>
class ACP
{
public:
ACP(const char* const init) : ourStr_(_strdup(init)), size_(strlen(init) + 1) { }
virtual ~ACP() { free(ourStr_); }
//
// casting operators
//
operator char* () { return ourStr_; }
operator const char* const () const { return ourStr_; }
operator const std::string() const { return ourStr_; }
protected:
// hide the default constructor
ACP() : ourStr_(NULL), size_(0) {}
// hide the copy constructor
ACP(const ACP& copy);
protected:
char* ourStr_;
size_t size_;
}; // ACP
void t(const std::string& val)
{
std::string s = val;
}
void test()
{
const ACP acp("hello");
std::string s = acp;
const std::string cs = acp;
t((std::string)acp);
t(acp);
char ch[50];
strcpy(ch, acp);
}
The new conflict seems to be between the char* and the std::string cast operators. Giving errors like so:
1>foo.cpp(36): error C2440: 'initializing' : cannot convert from 'const ACP' to 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>'
1> No constructor could take the source type, or constructor overload resolution was ambiguous
1>foo.cpp(37): error C2440: 'initializing' : cannot convert from 'const ACP' to 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>'
1> No constructor could take the source type, or constructor overload resolution was ambiguous
1>foo.cpp(38): error C2440: 'type cast' : cannot convert from 'const ACP' to 'std::string'
1> No constructor could take the source type, or constructor overload resolution was ambiguous
回答1:
With Visual Studio 2017, only the line
t((std::string)acp);
give a compilation error. Removing that cast and it compile without error.
There are many ways to fix that error. Some might not works with VS 2013.
t(std::move(acp)); // C++11
t(static_cast<const std::string &>(acp));
But casting is generally not a good idea so adding a method str()
to ACP might be a good idea. Or add an overload to t
that takes a const ACP &
.
If you can use a compiler that support C++ 11, the an overload of t
that takes a std::string &&
might make sense too.
来源:https://stackoverflow.com/questions/45446385/trouble-with-cast-operators-converting-to-visual-studio-2013