vsprintf or sprintf with named arguments, or simple template parsing in PHP

Late to the party, but you can simply use strtr to “translate characters or replace substrings” <?php $hours = 2; $minutes = 24; $seconds = 35; // Option 1: Replacing %variable echo strtr( ‘Last time logged in was %hours hours, %minutes minutes, %seconds seconds ago’, [ ‘%hours’ => $hours, ‘%minutes’ => $minutes, ‘%seconds’ => $seconds … Read more

compile time loops

Nope, it’s not directly possible. Template metaprogramming is a pure functional language. Every value or type defined through it are immutable. A loop inherently requires mutable variables (Repeatedly test some condition until X happens, then exit the loop). Instead, you would typically rely on recursion. (Instantiate this template with a different template parameter each time, … Read more

How to ensure that the template parameter is a subtype of a desired type?

Given some complete type MyBase, the following will yield a compile-time error if T is not derived from MyBase: #include <boost/type_traits/is_base_of.hpp> #include <boost/static_assert.hpp> template<typename T> class Foo { BOOST_STATIC_ASSERT_MSG( (boost::is_base_of<MyBase, T>::value), “T must be a descendant of MyBase” ); // Foo implementation as normal }; If you’re using a C++03 compiler with TR1, you can … Read more

If I want to specialise just one method in a template, how do I do it?

You can provide a specialization for only that function outside the class declaration. template <typename T> struct Node { // general method split void split() { // implementation here or somewhere else in header } }; // prototype of function declared in cpp void splitIntNode( Node & node ); template <> void Node<int>::split() { splitIntNode( … Read more

How does the linker handle identical template instantiations across translation units?

C++ requires that an inline function definition be present in a translation unit that references the function. Template member functions are implicitly inline, but also by default are instantiated with external linkage. Hence the duplication of definitions that will be visible to the linker when the same template is instantiated with the same template arguments … Read more

c++ template and header files [duplicate]

Headers. It’s because templates are instantiated at compile-time, not link-time, and different translation units (roughly equivalent to your .cpp files) only “know about” each other at link-time. Headers tend to be widely “known about” at compile-time because you #include them in any translation unit that needs them. Read https://isocpp.org/wiki/faq/templates for more.

tech