lambda meets template

In cpp, java and c#, The worst part of lambda is the integration with (parametrized) templates.

In each case, We need to understand the base technology and how that integrates with templates, otherwise you will be lost. The base technologies are (see post on “lambda – replicable”)
– delegate
– anon nested class
– functor

Syntax is bad but not the worst. Don’t get bogged down there.

c++ OO vs templates – evolution from C

Am no expert on language evolution, but I feel c++ extends C primarily in two directions — 1) OO and 2) templates (and perhaps 3) exceptions)

Most introductory texts focus on OO. C++ sister (derivative) languages — java, c# etc — focused mostly on enhancing the c++ OO features and only added templates as an afterthought. OO, not template, has been the dominant paradigm since the 90’s. In contrast, I feel the art of template meta-programming feels kind of a dark and dying art.
Compared to OO, I feel c++ template meta-programming is more powerful more complex. Note STL is all template and no virtual function. I guess so are many popular Boost libraries.
C++ OO can become unwieldy (MI, hiding, slicing etc) and was significantly simplified in java. In comparison, I feel c++ template techniques are even more complex.
When a language feature becomes so complex, the number of competent practitioners will remain small. Case in point — threading. Most developers stick to battle-tested threading constructs only. Similarly, most app dev teams don’t bother to create templates except those trivial 50-line templates.
In fact, as of 2013, many active and influential projects are based on C not C++. With respect to language evolution, i don’t think any language has embraced the c++ template meta programming heritage wholesale, and is carrying the torch. Many new languages are more dynamic, simpler to use, and OO. They are based on C or JVM, not c++.

template type arg constraints – c++ vs java

java and c# templates can have constraints. If the template uses T->length() then the constraint says T must subtype a certain interface containing a length() method. C++ handles it differently.

(http://stackoverflow.com/questions/874298/c-templates-that-accept-only-certain-types presents other solutions like boost static_assert…)

http://stackoverflow.com/questions/122316/template-constraints-c points out

You can call any functions you want upon a template-typed value, and the only instantiations that will be accepted are those for which that method is defined. For example:

template
int compute_length(T *value)
{
return value->length();
}
We can call this method on a pointer to any type which declares the length() method to return an int. Thusly:
string s = “test”;
vector vec;
int i = 0;

compute_length(&s);
compute_length(&vec);

…but not on a pointer to a type which does not declare length():
compute_length(&i);

This third example will not compile.

This works because C++ compiles a new version of the template function (or class) for each instantiation. As it performs that compilation, it makes a direct, almost macro-like substitution of the template instantiation into the code prior to type-checking. If everything still works with that template, then compilation proceeds and we eventually arrive at a result. If anything fails (like int* not declaring length()), then we get the dreaded six page template compile-time error.

%%jargon — describing c++ templates

The official terminology describing class templates is clumsy and inconsistent with java/c#. Here’s my own jargon. Most of the words (specialize, instantiate) already have a technical meaning, so I have to pick new words like “concretize” or “generic”

Rule #1) The last Word is key. Based on [[C++FAQ]]
– a class-template — is a template not a class.
– a concretized template-class — is a class not a template
————————–

“concretizing” a template… Officially terminology is “instantiating”

A “concretized class” = a “template class”. Don’t’ confuse it with — “concrete” class means non-abstract

A “unconcretized / generic class template” = a “class template”.
(Note I won’t say “unconcretized class”as it’s self-contradictory.)

A “non-template” class is a regular class without any template.

Note concretizing = instantiating, completely different from specializing!

“dummy type name” is the T in the generic vector

“type-argument”, NOT “parameter“, refers to an actual, concrete type like the int in vector

func ptr as template non-type param

This is the #1 eye-opener in [[essential c++]]

http://bigblog.tanbin.com/2012/03/non-dummy-type-template-parameters.html describes the background of Non-Dummy-Type parameters in a class template. Things like the maxRows in template class matrix_double. [[Essential c++]] succinctly describes that usage but also illustrates on P185 how you can put in a func ptr Type (not a dummy type) in place of the “int maxRows”. I find it a very powerful technique. (I guess java and c# take other routes since they don’t support NDT template parameters.) This is how I guess it works. 

First understand a real usage scenario and focus on a concrete class instantiated from such a template. At runtime such a class can have 888 class-instances, but they all share a single special “static field”, which is the function address[1] supplied to concretize the template.
If you later concretize the template with a 2nd function address, you get a 2nd concrete class. You can create 877 instances of this 2nd class. 
For the simple NDT, you supply an integer constant like 55 when you concretize the template matrix_double. Similarly, you supply a function address as a constant when concritizing our numeric_sequence template. More generally, any constant expression can be used for a NDT.
How useful is this technique? It allows you to concretize a template using a specific function address — a specific “behavior”. It could beat a static field in some cases. For example, You can concretize a given template
* once with type Account + AccountBehavior
* once with type Student + StudentBehavior
* once with type int + intBehavior
[1] the address of a real function, not a func ptr Type.

c++ template technicality – IKM findings

Never quizzed when I declare I’m no template wizard…

to specialize a func template,

template <typename T> void fn(T a){}
template<  > void fn(char c){…} //empty param to specialize an existing func template

template<class T> void f(T arg){ cout<<arg<<endl;}
template<> void f<char>(char arg){ cout<<"char: "<<arg<<endl;}
// the <char> after f is optional !
int main() {
  f(1.3);
  f('a');
}
///////////////// Some<int> is distinct from Some<char> --
template <typename T> class Some{
  public: static int stat;
};

template<typename T> int Some<T>::stat = 10;
int main(){
  Some<int>::stat = 5;
  cout<<Some<int>::stat<<endl;
  cout<<Some<char>::stat<<endl;
  cout<<Some<short>::stat<<endl;
  cout<<Some<long>::stat<<endl;
}

c++syntax – class template – brief notes

[[absolutionC++]] covers ordinary class template and subclassing an /unconcretized/ class template. The syntax can be quite “flexible”. I guess some compilers might allow you to omit a symbol here or there. I prefer to follow the full syntax, same habit as with c# lambda expressions. Less likely to confuse myself when reading the code 6 months later.

In practice, we just need to follow a consistent syntax that works. No need to know if some unusual syntax is standard-conforming or not. But on some occasions like online quizzes, we may need to play the language lawyer. Let’s look at one simple aspect — It’s good to know where the dummy type name “T” or “S” should (not) be repeated.

After template , and when we first name our new class, we don’t put on its head —

template class BB   {};

However, subclassing this base class uses slightly different syntax —

template class DD: public BB{};

For an IKM c++ quiz, I used windows gcc to FAIL all of the below —

template class DD: public BB{}; //WRONG – new template must not be “decorated”
template class DD: public BB{}; // WRONG – base template must be “decorated”
template class DD: public BB{}; //WRONG – breaking both rules

Q: Do we ever use the class template BB without a concrete type and without a dummy type?
%%A: I haven’t seen any example. Looks like non-standard or obscure syntax

template expansion/instantiation c++^c#[[pro .Net perf]]

— Based on P154 [[pro .net performance]] —

A regular c++ class Dog has 2 forms i.e. source file and the compiled binary file (usually as a library).

In contrast, a c++ class template like a simple BigList has 1 form only. There’s no such thing as a compiled form of a class template (unlike java/c#). The BigList source is used only when we compile a concretized class based on the template, such as BigList. If we include BigList source in a project but never use it, then the compiler probably ignores it.

If BigList defines a method dance() that’s not used in BigList, then this method is ignored by the compiler. In contrast, an invoked method (such as add()) is “expanded” with the type-argument “string”, to become a concretized method, and then compiled. I feel the expansion mechanism is similar to macro expansion.

What if dance() contains something unsupported by string? Well, rest assured — not compiled.

In C#, BigList is not an “expanded” or concretized version of BigList.