All this time I've been using alias
, but today I discovered by chance that D has typedef
. Interesting enough, TDPL doesn't even cover it as far as I can tell (not even listed in D Keywords
nor the Errata). The site does cover it, but it doesn't talk about it much. My code compiles with either, but what is the difference between the two, and when should I use typedef
over alias
?
typedef is a reserved keyword in the programming languages C and C++. It is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type.
In C++, 'using' and 'typedef' performs the same task of declaring the type alias. There is no major difference between the two. 'Using' in C++ is considered to define the type synonyms. This method is also known as alias- declaration.
Difference between the typedef and the #define in CTypedef is a keyword in the C programming language. #define is a pre-processor and used as macro used in C programming. 2. It is a keyword used to provide an alternate name to the existing data types only.
We can have symbolic names to datatypes using typedef but not to numbers etc. Whereas with a macro, we can represent 1 as ONE, 3.14 as PI and many more. We can have a type name and a variable name as same while using typedef. Compiler differentiates both.
alias
creates a new name for an existing one. typedef
only works on types, and actually creates a new type:
alias int A;
typedef int B;
pragma(msg, is(A == int)); // true
pragma(msg, is(B == int)); // false
With typedef
, you can also change the default initializer:
typedef int A = 42;
A a;
A[5] b;
void main()
{
assert(a == 42);
foreach(i; b) assert(i == 42);
}
alias
is more general. It also works with symbols:
import std.stdio;
import std.conv : to;
alias to!(string) toString;
void main()
{
int a;
alias a b;
a = 1;
writeln(b); // 1
string s = toString(2);
writeln(s); // 2
}
alias
is also used when you want to merge overload sets:
import std.stdio;
class Base
{
void foo() { writeln("base"); }
}
class Derived : Base
{
alias super.foo foo; // merge overload sets
void foo(int i) { writeln("derived"); }
}
void main()
{
auto a = new Derived;
a.foo(); // base
a.foo(0); // derived
}
Without the explicit merge, calling Base.foo
using an instance of Derived
is not allowed, because Derived.foo
hides it by default.
This isn't only required for classes; if functions from two different imported modules are to overload each other, they must be merged explicitly with alias
.
typedef
is deprecated. As of DMD version 2.057, using typedef
requires the -d
(for "deprecated") flag to compile.
This pull request adds a template TypeDef
to std.typecons
replicating the functionality of typedef
in the standard library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With