开发者

Conversion problem

开发者 https://www.devze.com 2022-12-10 12:59 出处:网络
I\'m using gcc 4.3.2. I have the following code (simplified): #include <cstdlib> template<int SIZE>

I'm using gcc 4.3.2.

I have the following code (simplified):

#include <cstdlib>

template<int SIZE>
class Buffer
{
public:
    explicit Buffer(const char *p = NULL) {}
    explicit Buffer(const Buffer &other);

    const char *c_str() const { return m_buffer; }

private:
    char m_buffer[SIZE];
};

typedef Buffer<10> A;
typedef Buffer<20> B;

void Foo(A a) {
}

int main()
{
    B b;
    Foo(b.c_str());  // line 25 fails compilation
    return 1;
}

Compilation yields:

test.cpp: In function ‘int main()’:
test.cpp:25: error: conversion from ‘const char*’ to non-scalar type ‘A’ requested

But there's c-tor receiving const char *.

UDP:

If I remove explicit from 1st c-tor I receive

test.cpp: In function ‘int main()’:
test.cpp:25: error: no matching function for cal开发者_StackOverflow中文版l to ‘Buffer<10>::Buffer(A)’
test.cpp:7: note: candidates are: Buffer<SIZE>::Buffer(const char*) [with int SIZE = 10]
test.cpp:25: error:   initializing argument 1 of ‘void Foo(A)’

If I use Foo(A(b.c_str())) I receive:

test.cpp: In function ‘int main()’:
test.cpp:25: error: no matching function for call to ‘Buffer<10>::Buffer(A)’
test.cpp:25: error:   initializing argument 1 of ‘void Foo(A)’


Your conversion constructor is declared explicit. Keyword explicit is specifically intended to prevent implicit conversions by that constructor. And an implicit conversion is exactly what you expect to happen in your code (at the Foo call).

Why did you declare your constructor explicit, if you want it to work in implicit conversions?


A and B are totally different types. As Andrey pointed out, there is no implicit callable constructor for conversion. You'll have to write

Foo(A(b.c_str()));

This will create a temporary 'automatic' (unnamed) object of type A using the explicit constructor for const char. And this will be passed to Foo.

0

精彩评论

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