Bug 4875 – Allow struct initialization with constructor

Status
RESOLVED
Resolution
WONTFIX
Severity
enhancement
Priority
P2
Component
dlang.org
Product
D
Version
D2
Platform
All
OS
All
Creation time
2010-09-15T14:45:00Z
Last change time
2012-01-23T23:04:11Z
Keywords
spec
Assigned to
nobody
Creator
dfj1esp02

Comments

Comment #0 by dfj1esp02 — 2010-09-15T14:45:38Z
If we have a struct --- struct HANDLE { size_t Value=-1; this(void *ptrValue) { Value=cast(size_t)ptrValue; } this(size_t intValue) { Value=intValue; } } --- it's possible to initialize variables of type HANDLE with values of types void* and size_t: --- HANDLE h1=4, h2=null; --- But it's impossible to initialize class fields and function arguments in the same way: --- class File { HANDLE Handle=5; //cannot implicitly convert expression (5) of type int to HANDLE } void FFFF(HANDLE){} FFFF(5); FFFF(null); //cannot implicitly convert expression (null) of type void* to HANDLE --- This complicates porting from C because in C it's a common practice to pass null as a function argument for a handle value.
Comment #1 by bearophile_hugs — 2010-09-15T14:49:30Z
You may write this: class File { HANDLE Handle = HANDLE(5); }
Comment #2 by dfj1esp02 — 2010-09-15T15:59:47Z
The code should be still source-compatible with alias void* HANDLE;
Comment #3 by bearophile_hugs — 2010-09-15T16:18:13Z
Is this good enough? struct HANDLE { size_t value = -1; // variables are lowercase in D this(void *ptrValue) { value = cast(size_t)ptrValue; } this(size_t intValue) { value = intValue; } void opAssign(void *ptrValue) { value = cast(size_t)ptrValue; } void opAssign(size_t intValue) { value = intValue; } } // alias size_t HANDLE; class File { HANDLE handle; this() { handle = 5; } } void main() {}
Comment #4 by dfj1esp02 — 2010-09-16T15:36:08Z
(In reply to comment #1) > You may write this: > > class File { > HANDLE Handle = HANDLE(5); > } Hmm... giving it another thought, forcing explicit constructor syntax can be ok: it makes things explicit and with proper OO wrapping doesn't require big changes.
Comment #5 by bugzilla — 2012-01-23T23:04:11Z
Allowing such implicit conversions works in C++, but is considered a defect by experienced C++ professionals. We won't repeat the mistake.