Template Metaprogramming Flashcards
What are template functions?
When we write the templates of functions that don’t necessarily explicitly specify the types of parameters/return types for function.
What does it mean that template functions are candidate functions?
When you attempt to use a function, the compiler will search for all templated functions and try to find a suitable candidate.
What happens if a compiler find a suitable templated function?
It will create an instance of that function for the specified types.
What is each instance of a template function in the binary?
Each instance of the templated function is a different function in the binary.
Where do we write template functions?
Only in the header files. As they are not implementations.
How do constrain templates?
Using them in a way that defines their behaviour. E.g. using them in a to string function means type must support «_space;operator
Why might template functions printing a class not work?
Because the print function of a class might not be defined.
What happens to function calls during linking in compilation?
During compilation, when the compiler comes across a function call it must resolve that function call to a specific instance of a function.
During linking what happens if there is a perfectly matching implemented function?
It will link the call to the function implementation.
During linking what happens if there is not a perfectly matching implemented function?
- The compiler will look through all the template functions
What happens in you include a template in an implementation file that wasn’t used?
The template would not be included in an object file. (Why it needs to be in a header file)
What happens during linking in template metaprogramming?
During compilation, if the compiler reaches a call to a function that has no implementation, rather than throw and error and abort compilation, it will try to find a candidate function to create a specialisation of it.
What is the compiler process for finding candidate function?
- Compiler creates a set of all functions with a matching name
- Then tries to substitute in the type(s) from the call into the implementation
- If one matches, the compiler will create an instance of the specialisation of the function for a given type
- If one doesn’t match, it will move onto the next template in the set
- An error only unfolds if there are no possible candidate template functions
(Process also known as SFINAE)
What does SFINAE stand for?
Substitution Failure Is Not An Error
What is SFINAE?
The concept of metaprogramming where the compiler tries to find a candidate function.