Is there anything in the C++0x standard to support separate compilation of templates? - g++

In current g++, I typically include all my templated functions that take the template parameter as an argument because they have to be compiled for each instance.
template<typename T>
class A {
public:
void f() { ... }
};
So in a different source, I would write:
#include <A.hh>
A<int> a1;
a1.f();
A<double> a2;
a2.f();
Sometimes, when I've been desperate to not inline big methods, I've manually specified which classes will be used in the source file, but it's really obnoxious:
template<typename T>
A::A() { ... }
template<typename T>
void A::f() { ... }
A<int>; // manually trigger code generation for int and double
A<double>;
Obviously different IDEs and compilers have mechanisms to support this. Is there anything standard that has been mandated, and/or does g++ support anything like this?

There's nothing in the proposed C++0x standard. In fact, export template has been removed (few compilers implemented it anyway).
As far as inlining is concerned, it's a total non-issue. The compiler is smart enough not to inline functions which are too big, even if they're marked inline and put into a header file.
If you're looking at increased compile times from header files grown bloated from templates, use precompiled headers. These aren't standard, but almost all current compilers provide such a mechanism.

C++0x does have extern template, which allows you to prevent the instantiation of certain templates in a compilation unit. So if you have a template class SomeClass, you can put this in the header:
extern template SomeClass<int>;
extern template SomeClass<double>;
This will prevent users from instantiating the template. In the .cpp file for the template, you can force instantiation with this syntax:
template SomeClass<int>;
template SomeClass<double>;

I've manually specified which classes will be used in the source file, but it's really obnoxious:
A<int>; // manually trigger code generation for int and double
A<double>;
This is not legal (I assume you meant to declare dummy variables here, and missed their name). We will see below why
Is there anything standard that has been mandated, and/or does g++ support anything like this?
C++03 had something called export, but which turned out to be a misfeature. The EDG implemented that feature, and their experience with it indicated that it's not worth the trouble implementing it. And it doesn't provide a useful feature separate compilation usually gives you: Hiding of the code of templates which you once compiled. export still requires the code of templates, be it in raw form or encoded into a mid-level compiler-specific language. See Why we can't afford export. A short example is given by EDG worker David Vandevoorde here.
For C++0x and for C++0x sans export, we have
A function template, member function of a class template, or static data member of a class template shall be defined in every translation unit in which it is implicitly instantiated (14.7.1) unless the corresponding specialization is explicitly instantiated (14.7.2) in some translation unit; no diagnostic is required
As this indicates, the only way you can achieve separate compilation is to explicitly instantiate the template you want to have separately compiled. By defining dummy variables, you merely implicitly instantiate the class template. And you do not instantiate the member functions of the class templates that way - you would need to do dummy calls or take their address. And to all this, you are not guaranteed that an implicitly instantiated function won't be discarded if it's not used in the translation unit it was instantiated by, after optimization, based on the above quote.
So you explicitly instantiate the class template, which will explicitly also instantiate its member functions the following way:
template class A<int>;
template class A<double>;

This feature, called export is present even in the current standard of C++. Unfortunately, most compilers, including gcc, do not support it. See here http://gcc.gnu.org/bugs/

Related

Kotlin: Idiomatic usage of extension functions - putting extension functions next to the class it extends

I see some usages of Extension functions in Kotlin I don't personally think that makes sense, but it seems that there are some guidelines that "apparently" support it (a matter of interpretation).
Specifically: defining an extension function outside a class (but in the same file):
data class AddressDTO(val state: State,
val zipCode: String,
val city: String,
val streetAddress: String
)
fun AddressDTO.asXyzFormat() = "${streetAddress}\n${city}\n${state.name} $zipCode"
Where the asXyzFormat() is widely used, and cannot be defined as private/internal (but also for the cases it may be).
In my common sense, if you own the code (AddressDTO) and the usage is not local to some class / module (hence behing private/internal) - there is no reason to define an extension function - just define it as a member function of that class.
Edge case: if you want to avoid serialization of the function starting with get - annotate the class to get the desired behavior (e.g. #JsonIgnore on the function). This IMHO still doesn't justify an extension function.
The counter-response I got to this is that the approach of having an extension function of this fashion is supported by the Official Kotlin Coding Conventions. Specifically:
Use extension functions liberally. Every time you have a function that works primarily on an object, consider making it an extension function accepting that object as a receiver.
Source
And:
In particular, when defining extension functions for a class which are relevant for all clients of this class, put them in the same file where the class itself is defined. When defining extension functions that make sense only for a specific client, put them next to the code of that client. Do not create files just to hold "all extensions of Foo".
Source
I'll appreciate any commonly accepted source/reference explaining why it makes more sense to move the function to be a member of the class and/or pragmatic arguments support this separation.
That quote about using extension functions liberally, I'm pretty sure means use them liberally as opposed to top level non-extension functions (not as opposed to making it a member function). It's saying that if a top-level function conceptually works on a target object, prefer the extension function form.
I've searched before for the answer to why you might choose to make a function an extension function instead of a member function when working on a class you own the source code for, and have never found a canonical answer from JetBrains. Here are some reasons I think you might, but some are highly subject to opinion.
Sometimes you want a function that operates on a class with a specific generic type. Think of List<Int>.sum(), which is only available to a subset of Lists, but not a subtype of List.
Interfaces can be thought of as contracts. Functions that do something to an interface may make more sense conceptually since they are not part of the contract. I think this is the rationale for most of the standard library extension functions for Iterable and Sequence. A similar rationale might apply to a data class, if you think of a data class almost like a passive struct.
Extension functions afford the possibility of allowing users to pseudo-override them, but forcing them to do it in an independent way. Suppose your asXyzFormat() were an open member function. In some other module, you receive AddressDTO instances and want to get the XYZ format of them, exactly in the format you expect. But the AddressDTO you receive might have overridden asXyzFormat() and provide you something unexpected, so now you can't trust the function. If you use an extension function, than you allow users to replace asXyzFormat() in their own packages with something applicable to that space, but you can always trust the function asXyzFormat() in the source package.
Similarly for interfaces, a member function with default implementation invites users to override it. As the author of the interface, you may want a reliable function you can use on that interface with expected behavior. Although the end-user can hide your extension in their own module by overloading it, that will have no effect on your own uses of the function.
For what it's worth, I think it would be very rare to choose to make an extension function for a class (not an interface) when you own the source code for it. And I can't think of any examples of that in the standard library. Which leads me to believe that the Coding Conventions document is using the word "class" in a liberal sense that includes interfaces.
Here's a reverse argument…
One of the main reasons for adding extension functions to the language is being able to add functionality to classes from the standard library, and from third-party libraries and other dependencies where you don't control the code and can't add member functions (AKA methods).  I suspect it's mainly those cases that that section of the coding conventions is talking about.
In Java, the only option in this cases is utility methods: static methods, usually in a utility class gathering together lots of such methods, each taking the relevant object as its first parameter:
public static String[] splitOnChar(String str, char separator)
public static boolean isAllDigits(String str)
…and so on, interminably.
The main problem there is that such methods are hard to find (no help from the IDE unless you already know about all the various utility classes).  Also, calling them is long-winded (though it improved a bit once static imports were available).
Kotlin's extension methods are implemented exactly the same way down at the bytecode level, but their syntax is much simpler and exactly like member functions: they're written the same way (with this &c), calling them looks just like calling a member function, and your IDE will suggest them.
(Of course, they have drawbacks, too: no dynamic dispatch, no inheritance or overriding, scoping/import issues, name clashes, references to them are awkward, accessing them from Java or reflection is awkward, and so on.)
So: if the main purpose of extension functions is to substitute for member functions when member functions aren't possible, why would you use them when member functions are possible?!
(To be fair, there are a few reasons why you might want them.  For example, you can make the receiver nullable, which isn't possible with member functions.  But in most cases, they're greatly outweighed by the benefits of a proper member function.)
This means that the vast majority of extension functions are likely to be written for classes that you don't control the source code for, and so you don't have the option of putting them next to the class.

Why does ABAP divide classes into implementation and definition?

I know that ABAP Objects are kinda old but as far as my knowledge goes you still have to use at least two "sections" to create a complete class.
ABAP:
CLASS CL_MYCLASS DEFINITION.
PUBLIC SECTION.
...
PROTECTED SECTION.
...
PRIVATE SECTION.
...
ENDCLASS.
CLASS CL_MYCLASS IMPLEMENTATION.
...
ENDCLASS.
Java:
public class MyClass {
<visibility> <definition> {
<implementation>
}
}
Wouldn't it make development easier/faster by having a combination of both like most modern languages have?
What are the reasons for this separation?
Easier/faster for the human (maybe), but costly for the compiler: It has to sift through the entire code to determine the structure of the class and its members, whereas in the current form, it only needs to compile the definition to determine whether a reference is valid. ABAP is not the only language that separates definition from implementation: Pascal did so for units, and Object Pascal for classes. One might argue that C++ allows for same construct without specifying an implementation section when you're not using inline member function declarations.
Maybe another reason:
Most (?) classes are not defined with manual written code, but via SE24. There you define the interface in one dynpro and write the code in another one.
Internally the interfaces are stored in one source, the code is stored in another source. So it is reasonable to separate the interface and the implementation.

Static, extern and inline in Objective-C

What do static, extern and inline (and their combinations) mean in Objetive-C using the LLVM compiler?
Also, I noticed that there are CG_EXTERN and CG_INLINE macros. Should we be using those instead?
(I couldn't find a source with a clear explanation so I thought it might be useful to create one here, or point to it if someone knows one)
What do static, extern and inline (and their combinations) mean in Objetive-C using the LLVM compiler?
The same as in C, unless you compile as ObjC++ -- then they mean the same as found in C++.
So here is an introduction for C, but read the links if you are ready to use these because the details are important:
Extern
Summary: Indicates that an identifier is defined elsewhere.
Details: http://tigcc.ticalc.org/doc/keywords.html#extern
Static
Summary (value): Preserves variable value to survive after its scope ends.
Summary (function): Effectively emits unnamed copies - useful for private functions in C, and can be used to escape multiple definition errors when used with inline functions.
Details: http://tigcc.ticalc.org/doc/keywords.html#static
Inline
Summary: Suggests the body of a function should be moved into the callers.
Details: http://tigcc.ticalc.org/doc/gnuexts.html#SEC93
Note that inline and static are quite a bit more complex in C++ (like pretty much everything in C++).
I also found that there are CG_EXTERN and CG_INLINE macros. Should we be using those instead?
No.
Instead, you should specify your own, with your own meanings, if you need this type of functionality. CG_EXTERN and CG_INLINE have specific meanings (which may change), and are meant to be used in their defined context -- also, you don't want to have to include a whole handful of frameworks (all CoreGraphics/ApplicationServices/CoreFoundation/etc.) when you want to specify something is extern in a way that works in C and C++.
Justin covered most of it, but I found some other nice resources for those who want to dig deeper:
By declaring a function inline you tell the compiler to replace the complete code of that function directly into the place from where it was called. This is a rather advanced feature that requires understanding of lower-level programming.
Inline functions
This SO question has an enormous answer about extern variables - variables defined "somewhere else" - but need to be used also "here".
Static preserves variable life outside of scope. The Variable is visible within the scope it was declared.
What does a static variable mean?

interface of dll

I heard people talking about changing the interface of a dll.
What is a change in the interface of the dll, and how would you do that?
Changing a dll's interface would mean to change how the dll and the calling code interacts. This could mean changing the signatures of the dll's exporting functions, or changing to a different set of functions entirely, or it could mean passing different data from the calling code. A dll's interface is generally all it's exported and imported items (both functions and data), or in other words, the parts of the dll that you have access to when you use it.
Often you will want to change the behaviour of your dll without changing its interface. This is because changing the interface often will break code that uses it.
Imagine my dll exporting function foo:
void foo(int i)
{
// Does thing with integer
}
Changing the interface could mean changing foo's signature into
void foo(int, float);
Now, all the code that used foo previously has to be rewritten to use the new signature, which could be a bad thing.

Can the gcc static linker properly inline functions from a static library?

If we compile a number of source codes which makes uses of a static library named lib.a, would the inline functions in lib.a get properly inlined with the rest of binaries?
no, they would not. Inlining is an operation on the parse tree and requires access to the source code for both the host and donor sources of the inlined code.
Static libraries have already been compiled from source to binary at the point you use them, so inlining cannot happen.
However, code that is not inlined is also 'proper' and will function just fine (assuming it got compiled into the static library at all).
Well, since in order to even attempt to call an inline function its declaration must be visible at the call site. If it is then inline then the compiler will either inline it or completely ignore the request.
If you are wondering if functions NOT declared inline that were inlined in the library can then also be inlined when you link to the final product...this would depend on the implementation and, assuming it is already capable of LTO (since it did it to the library), it very well might be able to inline them again. You may be required to cause the implementation to include the definition even when it's been inlined everywhere though...all depends on the implementation.
http://crazyeddiecpp.blogspot.com/2010/12/inline-functions-and-you.html