开发者

MSVS2008 compiler cannot find implicit type conversion: cannot convert parameter 1 from 'SrcT' to 'DstT'

开发者 https://www.devze.com 2023-04-05 23:58 出处:网络
Why my MSVS2008 compiler is not able to find 开发者_如何学JAVAimplicit type conversion SrcT -> LPCSTR -> DstT when calling a function? This works fine in other cases. I do not like writing manual conv

Why my MSVS2008 compiler is not able to find 开发者_如何学JAVAimplicit type conversion SrcT -> LPCSTR -> DstT when calling a function? This works fine in other cases. I do not like writing manual conversion all the time like following: MyFunc((LPCSTR)src). What I'm missing?

    MyFunc(src);

1>d:\test\test.cpp(39) : error C2664: 'MyFunc' : cannot convert parameter 1 from 'SrcT' to 'DstT'

#include <windows.h>
#include <tchar.h>

class SrcT
{
public:
    operator LPCSTR() const
    {
        return "dummy";
    }
};

class DstT
{
public:
    DstT() : m_value(NULL) {};
    DstT(LPCSTR value) {m_value = value; }
    DstT& operator=(LPCSTR value) { m_value = value; return *this; }

    LPCSTR m_value;
};

void MyFunc(DstT dst)
{
}

int _tmain(int argc, _TCHAR* argv[])
{
    SrcT src;
    DstT dst(src);
    DstT dst2;

    dst2 = src;
    MyFunc((LPCSTR)src);
    MyFunc(src);

    return 0;
}


It's not just VS2008, all C++ compilers behave this way.

Two conversions are necessary to convert a SrcT to a DstT (SrcT->LPCSTR->DstT). However, the C++ standard states that only one user-defined conversion can be implicitly applied to a single value.

Section 12.3, Conversions

4 At most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value.

class X { // ...
    public:
        operator int();
};
class Y { // ...
    public:
        operator X();
};
Y a;
int b = a;    // error: a.operatorX().operator int() not tried
int c = X(a); // OK: a.operatorX().operator int()

See also this question.

0

精彩评论

暂无评论...
验证码 换一张
取 消