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 call 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. Keywordexplicitis specifically intended to prevent implicit conversions by that constructor. And an implicit conversion is exactly what you expect to happen in your code (at theFoocall).Why did you declare your constructor
explicit, if you want it to work in implicit conversions?