template-meta-programming

C++ templates Turing-complete?

Deadly 提交于 2019-11-26 04:05:11
问题 I\'m told that the template system in C++ is Turing-complete at compile time. This is mentioned in this post and also on wikipedia. Can you provide a nontrivial example of a computation that exploits this property? Is this fact useful in practice? 回答1: Example #include <iostream> template <int N> struct Factorial { enum { val = Factorial<N-1>::val * N }; }; template<> struct Factorial<0> { enum { val = 1 }; }; int main() { // Note this value is generated at compile time. // Also note that

Creating an array initializer from a tuple or variadic template parameters

无人久伴 提交于 2019-11-26 03:46:00
问题 I want to represent the description of a persistent memory layout (e.g. Flash or EEPROM device) statically embedded in the program code (preferably in the ROM section), from a set of variadic template parameters, where the necessary offsets are automatically calculated at compile time. The goal is to create an appropriate array initializer, that can be iterated at runtime, without the restrictions you\'ll get with std::get(std::tuple), which requires compile time indexing. 1st approach I have

Metaprograming: Failure of Function Definition Defines a Separate Function

混江龙づ霸主 提交于 2019-11-26 02:24:53
问题 In this answer I define a template based on the type\'s is_arithmetic property: template<typename T> enable_if_t<is_arithmetic<T>::value, string> stringify(T t){ return to_string(t); } template<typename T> enable_if_t<!is_arithmetic<T>::value, string> stringify(T t){ return static_cast<ostringstream&>(ostringstream() << t).str(); } dyp suggests that rather than the is_arithmetic property of the type, that whether to_string is defined for the type be the template selection criteria. This is

Is it possible to write a template to check for a function&#39;s existence?

僤鯓⒐⒋嵵緔 提交于 2019-11-25 23:55:46
问题 Is it possible to write a template that changes behavior depending on if a certain member function is defined on a class? Here\'s a simple example of what I would want to write: template<class T> std::string optionalToString(T* obj) { if (FUNCTION_EXISTS(T->toString)) return obj->toString(); else return \"toString not defined\"; } So, if class T has toString() defined, then it uses it; otherwise, it doesn\'t. The magical part that I don\'t know how to do is the \"FUNCTION_EXISTS\" part. 回答1:

How can you iterate over the elements of an std::tuple?

泄露秘密 提交于 2019-11-25 22:25:55
问题 How can I iterate over a tuple (using C++11)? I tried the following: for(int i=0; i<std::tuple_size<T...>::value; ++i) std::get<i>(my_tuple).do_sth(); but this doesn\'t work: Error 1: sorry, unimplemented: cannot expand ‘Listener ...’ into a fixed-length argument list. Error 2: i cannot appear in a constant expression. So, how do I correctly iterate over the elements of a tuple? 回答1: Boost.Fusion is a possibility: Untested example: struct DoSomething { template<typename T> void operator()(T&