tags:

views:

168

answers:

5

I want to be able to use a function such as writefln() but without having to add "import std.stdio" at the top of the file.

Another way to explain it is the way you do it in C++. You can type "std::cout << "Test";" and that will stop you from having to add "using namespace std;". I want to do the same thing but in D.

+2  A: 

I don't think you can do that. The import statement in D does more than the using namespace statement does in C++. It also replaces the #include preprocessor directive.

Ferruccio
+4  A: 

You have to use the import part. However it is possible to address a method/function/whatever with the full module path in front of it. For example std.stdio.writefln("...") would be valid if you import std.stdio (and use Phobos). This can be useful if you have more then one function that is called "writefln".

Maurice Gilden
+3  A: 

As stated above, D modules are much more than C++ namespaces. D is a MODULAR language as well. Modules in D have constructors/destructors. Moreover, D has packages. Read more about modules and packages in D here: http://www.digitalmars.com/d/2.0/module.html .

Here is the most interesting part of what that page says:

Modules have a one-to-one correspondence with source files. The module name is the file name with the path and extension stripped off.

Modules automatically provide a namespace scope for their contents. Modules superficially resemble classes, but differ in that:

  • There's only one instance of each module, and it is statically allocated.
  • There is no virtual table.
  • Modules do not inherit, they have no super modules, etc.
  • Only one module per file.
  • Module symbols can be imported.
  • Modules are always compiled at global scope, and are unaffected by surrounding attributes or other modifiers.

Modules can be grouped together in hierarchies called packages.

Modules offer several guarantees: - The order in which modules are imported does not affect the semantics. - The semantics of a module are not affected by what imports it. - If a module C imports modules A and B, any modifications to B will not silently change code in C that is dependent on A.

+2  A: 

I know this is an old question, but I don't see the right answer, so I'm answering anyway.

Static Imports

Basic imports work well for programs with relatively few modules and imports. If there are a lot of imports, name collisions can start occurring between the names in the various imported modules. One way to stop this is by using static imports. A static import requires one to use a fully qualified name to reference the module's names:

static import std.stdio;

void main()
{
    writefln("hello!");            // error, writefln is undefined
    std.stdio.writefln("hello!");  // ok, writefln is fully qualified
}

Source

zildjohn01
A: 

You can import separate functions / classes (not sure about syntax):

import std.stdio: writef, writefln;
Alexander Malakhov