search
HomeBackend DevelopmentC++Is C Template Metaprogramming Turing-Complete?

Is C   Template Metaprogramming Turing-Complete?

Is C Templates Turing-complete?

A widely circulated claim is that C templates are Turing-complete at compile time. This means that templates can be used to represent and execute any computable function.

Example of a Computation

Here's a non-trivial example of a turing machine implemented in C 11 using templates:

#include <iostream>

template<bool c typename a b>
struct Conditional {
    typedef A type;
};

template<typename a typename b>
struct Conditional<false a b> {
    typedef B type;
};

template<typename...>
struct ParameterPack;

template<bool c typename="void">
struct EnableIf { };

template<typename type>
struct EnableIf<true type> {
    typedef Type type;
};

template<typename t>
struct Identity {
    typedef T type;
};

// define a type list 
template<typename...>
struct TypeList;

template<typename t typename... tt>
struct TypeList<t tt...>  {
    typedef T type;
    typedef TypeList<tt...> tail;
};

template
struct TypeList> {

};

template<typename list>
struct GetSize;

template<typename... items>
struct GetSize<typelist>> {
    enum { value = sizeof...(Items) };
};

template<typename... t>
struct ConcatList;

template<typename... first typename... second tail>
struct ConcatList<typelist>, TypeList<second...>, Tail...> {
    typedef typename ConcatList<typelist second...>, 
                                Tail...>::type type;
};

template<typename t>
struct ConcatList<t> {
    typedef T type;
};

template<typename newitem typename list>
struct AppendItem;

template<typename newitem typename...items>
struct AppendItem<newitem typelist>> {
    typedef TypeList<items... newitem> type;
};

template<typename newitem typename list>
struct PrependItem;

template<typename newitem typename...items>
struct PrependItem<newitem typelist>> {
    typedef TypeList<newitem items...> type;
};

template<typename list int n typename="void">
struct GetItem {
    static_assert(N > 0, "index cannot be negative");
    static_assert(GetSize<list>::value > 0, "index too high");
    typedef typename GetItem<typename list::tail n-1>::type type;
};

template<typename list>
struct GetItem<list> {
    static_assert(GetSize<list>::value > 0, "index too high");
    typedef typename List::type type;
};

template<typename list template typename...> class Matcher, typename... Keys>
struct FindItem {
    static_assert(GetSize<list>::value > 0, "Could not match any item.");
    typedef typename List::type current_type;
    typedef typename Conditional<matcher keys...>::value, 
                                 Identity<current_type>, 
                                 FindItem<typename list::tail matcher keys...>>
        ::type::type type;
};

template<typename list int i typename newitem>
struct ReplaceItem {
    static_assert(I > 0, "index cannot be negative");
    static_assert(GetSize<list>::value > 0, "index too high");
    typedef typename PrependItem<typename list::type typename replaceitem list::tail i-1 newitem>::type>
        ::type type;
};

template<typename newitem typename type typename... t>
struct ReplaceItem<typelist t...>, 0, NewItem> {
    typedef TypeList<newitem t...> type;
};

enum Direction {
    Left = -1,
    Right = 1
};

template<typename oldstate typename input newstate output direction move>
struct Rule {
    typedef OldState old_state;
    typedef Input input;
    typedef NewState new_state;
    typedef Output output;
    static Direction const direction = Move;
};

template<typename a typename b>
struct IsSame {
    enum { value = false }; 
};

template<typename a>
struct IsSame<a a> {
    enum { value = true };
};

template<typename input typename state int position>
struct Configuration {
    typedef Input input;
    typedef State state;
    enum { position = Position };
};

template<int a int b>
struct Max {
    enum { value = A > B ? A : B };
};

template<int n>
struct State {
    enum { value = n };
    static char const * name;
};

template<int n>
char const* State<n>::name = "unnamed";

struct QAccept {
    enum { value = -1 };
    static char const* name;
};

struct QReject {
    enum { value = -2 };
    static char const* name; 
};

#define DEF_STATE(ID, NAME) \
    typedef State<id> NAME ; \
    NAME :: name = #NAME ;

template<int n>
struct Input {
    enum { value = n };
    static char const * name;

    template<int... i>
    struct Generate {
        typedef TypeList<input>...> type;
    };
};

template<int n>
char const* Input<n>::name = "unnamed";

typedef Input InputBlank;

#define DEF_INPUT(ID, NAME) \
    typedef Input<id> NAME ; \
    NAME :: name = #NAME ;

template<typename config typename transitions> 
struct Controller {
    typedef Config config;
    enum { position = config::position };

    typedef typename Conditional(GetSize<typename config::input>::value) 
            (position),
        AppendItem<inputblank typename config::input>,
        Identity<typename config::input>>::type::type input;
    typedef typename config::state state;

    typedef typename GetItem<input position>::type cell;

    template<typename item typename state cell>
    struct Matcher {
        typedef typename Item::old_state checking_state;
        typedef typename Item::input checking_input;
        enum { value = IsSame<state checking_state>::value && 
                       IsSame<cell checking_input>::value
        };
    };
    typedef typename FindItem<transitions matcher state cell>::type rule;

    typedef typename ReplaceItem<input position typename rule::output>::type new_input;
    typedef typename rule::new_state new_state;
    typedef Configuration<new_input new_state max rule::direction>::value> new_config;

    typedef Controller<new_config transitions> next_step;
    typedef typename next_step::end_config end_config;
    typedef typename next_step::end_input end_input;
    typedef typename next_step::end_state end_state;
    enum { end_position = next_step::position };
};

template<typename input typename state int position transitions>
struct Controller<configuration state position>, Transitions, 
                  typename EnableIf<issame qaccept>::value || 
                                    IsSame<state qreject>::value>::type> {
    typedef Configuration<input state position> config;
    enum { position = config::position };
    typedef typename Conditional(GetSize<typename config::input>::value) 
            (position),
        AppendItem<inputblank typename config::input>,
        Identity<typename config::input>>::type::type input;
    typedef typename config::state state;

    typedef config end_config;
    typedef input end_input;
    typedef state end_state;
    enum { end_position = position };
};

template<typename input typename transitions startstate>
struct TuringMachine {
    typedef Input input;
    typedef Transitions transitions;
    typedef StartState start_state;
</typename></typename></inputblank></typename></state></issame></configuration></typename></new_config></new_input></transitions></cell></state></typename></typename></inputblank></typename></typename></id></n></int></int...></int></id></n></int></int></int></typename></a></typename></typename></typename></newitem></typelist></typename></typename></list></typename></typename></current_type></matcher></list></typename></list></list></typename></typename></list></typename></newitem></newitem></typename></typename></items...></newitem></typename></typename></t></typename></typelist></second...></typelist></typename...></typename...></typelist></typename...></typename></tt...></t></typename></typename...></typename></true></typename></bool></typename...></false></typename></bool></iostream>

The above is the detailed content of Is C Template Metaprogramming Turing-Complete?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C   Destructors: What are the advantages?C Destructors: What are the advantages?May 16, 2025 am 12:01 AM

C destructorsprovideseveralkeyadvantages:1)Theymanageresourcesautomatically,preventingleaks;2)Theyenhanceexceptionsafetybyensuringresourcerelease;3)TheyenableRAIIforsaferesourcehandling;4)Virtualdestructorssupportpolymorphiccleanup;5)Theyimprovecode

Mastering Polymorphism in C  : A Deep DiveMastering Polymorphism in C : A Deep DiveMay 14, 2025 am 12:13 AM

Mastering polymorphisms in C can significantly improve code flexibility and maintainability. 1) Polymorphism allows different types of objects to be treated as objects of the same base type. 2) Implement runtime polymorphism through inheritance and virtual functions. 3) Polymorphism supports code extension without modifying existing classes. 4) Using CRTP to implement compile-time polymorphism can improve performance. 5) Smart pointers help resource management. 6) The base class should have a virtual destructor. 7) Performance optimization requires code analysis first.

C   Destructors vs Garbage Collectors : What are the differences?C Destructors vs Garbage Collectors : What are the differences?May 13, 2025 pm 03:25 PM

C destructorsprovideprecisecontroloverresourcemanagement,whilegarbagecollectorsautomatememorymanagementbutintroduceunpredictability.C destructors:1)Allowcustomcleanupactionswhenobjectsaredestroyed,2)Releaseresourcesimmediatelywhenobjectsgooutofscop

C   and XML: Integrating Data in Your ProjectsC and XML: Integrating Data in Your ProjectsMay 10, 2025 am 12:18 AM

Integrating XML in a C project can be achieved through the following steps: 1) parse and generate XML files using pugixml or TinyXML library, 2) select DOM or SAX methods for parsing, 3) handle nested nodes and multi-level properties, 4) optimize performance using debugging techniques and best practices.

Using XML in C  : A Guide to Libraries and ToolsUsing XML in C : A Guide to Libraries and ToolsMay 09, 2025 am 12:16 AM

XML is used in C because it provides a convenient way to structure data, especially in configuration files, data storage and network communications. 1) Select the appropriate library, such as TinyXML, pugixml, RapidXML, and decide according to project needs. 2) Understand two ways of XML parsing and generation: DOM is suitable for frequent access and modification, and SAX is suitable for large files or streaming data. 3) When optimizing performance, TinyXML is suitable for small files, pugixml performs well in memory and speed, and RapidXML is excellent in processing large files.

C# and C  : Exploring the Different ParadigmsC# and C : Exploring the Different ParadigmsMay 08, 2025 am 12:06 AM

The main differences between C# and C are memory management, polymorphism implementation and performance optimization. 1) C# uses a garbage collector to automatically manage memory, while C needs to be managed manually. 2) C# realizes polymorphism through interfaces and virtual methods, and C uses virtual functions and pure virtual functions. 3) The performance optimization of C# depends on structure and parallel programming, while C is implemented through inline functions and multithreading.

C   XML Parsing: Techniques and Best PracticesC XML Parsing: Techniques and Best PracticesMay 07, 2025 am 12:06 AM

The DOM and SAX methods can be used to parse XML data in C. 1) DOM parsing loads XML into memory, suitable for small files, but may take up a lot of memory. 2) SAX parsing is event-driven and is suitable for large files, but cannot be accessed randomly. Choosing the right method and optimizing the code can improve efficiency.

C   in Specific Domains: Exploring Its StrongholdsC in Specific Domains: Exploring Its StrongholdsMay 06, 2025 am 12:08 AM

C is widely used in the fields of game development, embedded systems, financial transactions and scientific computing, due to its high performance and flexibility. 1) In game development, C is used for efficient graphics rendering and real-time computing. 2) In embedded systems, C's memory management and hardware control capabilities make it the first choice. 3) In the field of financial transactions, C's high performance meets the needs of real-time computing. 4) In scientific computing, C's efficient algorithm implementation and data processing capabilities are fully reflected.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft