mardi 1 août 2017

Trouble with cast operators converting to Visual Studio 2013

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,std::allocator>' 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,std::allocator>' 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

Aucun commentaire:

Enregistrer un commentaire