www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - how do I make an alias for a const version of an alias in D 2.0?

reply "Steven Schveighoffer" <schveiguy yahoo.com> writes:
I have an issue where I have a custom pointer type like so:

alias char * PCHAR;

I want a const version of this, but if I do this:

alias const(PCHAR) C_PCHAR;

C_PCHAR is still char *

here is some demonstrating code:

alias char * PCHAR;
alias const(PCHAR) C_PCHAR;
alias const(char *) C_PCHAR2;


void main()
{
  pragma(msg, (const(PCHAR)).stringof);
  pragma(msg, C_PCHAR.stringof);
  pragma(msg, C_PCHAR2.stringof);
}

compiling this outputs:
const char*
char*
const char*

Note that using const(PCHAR) in the code and not in the alias results in the 
correct behavior

Is this a bug?  I'm using D 2.007.

-Steve 
Nov 06 2007
parent reply "Jarrett Billingsley" <kb3ctd2 yahoo.com> writes:
"Steven Schveighoffer" <schveiguy yahoo.com> wrote in message 
news:fgqcai$2900$1 digitalmars.com...

 alias char * PCHAR;
 alias const(PCHAR) C_PCHAR;
 alias const(char *) C_PCHAR2;


 void main()
 {
  pragma(msg, (const(PCHAR)).stringof);
  pragma(msg, C_PCHAR.stringof);
  pragma(msg, C_PCHAR2.stringof);
 }

 compiling this outputs:
 const char*
 char*
 const char*

I wouldn't necessarily trust the output of .stringof; it's known to be buggy in a lot of cases. See if you can get the compiler to spit out an error containing the type, i.e. void blah(T)() { SOME_INVALID_FUNCTION(); } ... blah!(PCHAR)(); This should make the compiler spit out some kind of error with the name of the instantiated blah, type included.
Nov 06 2007
parent "Steven Schveighoffer" <schveiguy yahoo.com> writes:
"Jarrett Billingsley" wrote
 I wouldn't necessarily trust the output of .stringof; it's known to be 
 buggy in a lot of cases.  See if you can get the compiler to spit out an 
 error containing the type, i.e.

 void blah(T)()
 {
    SOME_INVALID_FUNCTION();
 }

 ...

 blah!(PCHAR)();

 This should make the compiler spit out some kind of error with the name of 
 the instantiated blah, type included.

An actual problem of this very nature is what triggered my post, my example was a dumbed down version :) I assure you, the compiler is making the mistake, not stringof. Here is a clearer example: alias char * PCHAR; alias const(PCHAR) C_PCHAR; alias const(char *) C_PCHAR2; void f1(C_PCHAR arg) { } void f2(C_PCHAR2 arg) { } void main() { f1("hello"); f2("hello"); } compiler: testme.d(15): function testme.f1 (char*) does not match parameter types (invariant(char[5u])) testme.d(15): Error: cannot implicitly convert expression ("hello") of type invariant char[5u] to char* Note if I comment out the call to f1, the file compiles. -Steve
Nov 07 2007