개발/C++

C ++ 템플릿 Turing-complete?

MinorMan 2020. 9. 24. 00:39
반응형

<질문>

C ++의 템플릿 시스템은 컴파일 시간에 Turing-complete라고 들었습니다. 이것은이 게시물과 wikipedia에서도 언급됩니다.

이 속성을 활용하는 계산의 사소한 예를 제공 할 수 있습니까?

이 사실이 실제로 유용합니까?


<답변1>

#include 

template  struct Factorial
{
    enum { val = Factorial::val * N };
};

template<>
struct Factorial<0>
{
    enum { val = 1 };
};

int main()
{
    // Note this value is generated at compile time.
    // Also note that most compilers have a limit on the depth of the recursion available.
    std::cout << Factorial<4>::val << "\n";
}

약간 재미 있었지만 실용적이지는 않았습니다.

질문의 두 번째 부분에 답하려면 :이 사실이 실제로 유용합니까?

짧은 답변 : 일종의.

긴 답변 : 예,하지만 템플릿 데몬 인 경우에만 가능합니다.

다른 사람들이 (즉, 라이브러리) 사용하기에 정말 유용한 템플릿 메타 프로그래밍을 사용하여 좋은 프로그래밍을 만드는 것은 정말 어렵습니다. 부스트를 돕기 위해 MPL (Meta Programming Library)도 있습니다. 그러나 템플릿 코드에서 컴파일러 오류를 디버깅하면 오래 걸릴 것입니다.

그러나 유용한 것을 위해 사용되는 좋은 실용적인 예 :

Scott Meyers는 템플릿 기능을 사용하여 C ++ 언어 (저는 용어를 느슨하게 사용함)에 대한 확장을 작업했습니다. 여기에서 그의 작업에 대해 읽을 수 있습니다. '코드 기능 적용'


<답변2>

나는 C ++ 11로 튜링 머신을 만들었다. C ++ 11이 추가하는 기능은 실제로 튜링 머신에 중요하지 않습니다. 비뚤어진 매크로 메타 프로그래밍을 사용하는 대신 가변 템플릿을 사용하여 임의 길이 규칙 목록을 제공합니다. :). 조건의 이름은 stdout에 다이어그램을 출력하는 데 사용됩니다. 샘플을 짧게 유지하기 위해 해당 코드를 제거했습니다.

#include 

template
struct Conditional {
    typedef A type;
};

template
struct Conditional {
    typedef B type;
};

template
struct ParameterPack;

template
struct EnableIf { };

template
struct EnableIf {
    typedef Type type;
};

template
struct Identity {
    typedef T type;
};

// define a type list 
template
struct TypeList;

template
struct TypeList  {
    typedef T type;
    typedef TypeList tail;
};

template<>
struct TypeList<> {

};

template
struct GetSize;

template
struct GetSize> {
    enum { value = sizeof...(Items) };
};

template
struct ConcatList;

template
struct ConcatList, TypeList, Tail...> {
    typedef typename ConcatList, 
                                Tail...>::type type;
};

template
struct ConcatList {
    typedef T type;
};

template
struct AppendItem;

template
struct AppendItem> {
    typedef TypeList type;
};

template
struct PrependItem;

template
struct PrependItem> {
    typedef TypeList type;
};

template
struct GetItem {
    static_assert(N > 0, "index cannot be negative");
    static_assert(GetSize::value > 0, "index too high");
    typedef typename GetItem::type type;
};

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

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

template
struct ReplaceItem {
    static_assert(I > 0, "index cannot be negative");
    static_assert(GetSize::value > 0, "index too high");
    typedef typename PrependItem::type>
        ::type type;
};

template
struct ReplaceItem, 0, NewItem> {
    typedef TypeList type;
};

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

template
struct Rule {
    typedef OldState old_state;
    typedef Input input;
    typedef NewState new_state;
    typedef Output output;
    static Direction const direction = Move;
};

template
struct IsSame {
    enum { value = false }; 
};

template
struct IsSame {
    enum { value = true };
};

template
struct Configuration {
    typedef Input input;
    typedef State state;
    enum { position = Position };
};

template
struct Max {
    enum { value = A > B ? A : B };
};

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

template
char const* State::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 NAME ; \
    NAME :: name = #NAME ;

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

    template
    struct Generate {
        typedef TypeList...> type;
    };
};

template
char const* Input::name = "unnamed";

typedef Input<-1> InputBlank;

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

template 
struct Controller {
    typedef Config config;
    enum { position = config::position };

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

    typedef typename GetItem::type cell;

    template
    struct Matcher {
        typedef typename Item::old_state checking_state;
        typedef typename Item::input checking_input;
        enum { value = IsSame::value && 
                       IsSame::value
        };
    };
    typedef typename FindItem::type rule;

    typedef typename ReplaceItem::type new_input;
    typedef typename rule::new_state new_state;
    typedef Configuration::value> new_config;

    typedef Controller 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
struct Controller, Transitions, 
                  typename EnableIf::value || 
                                    IsSame::value>::type> {
    typedef Configuration config;
    enum { position = config::position };
    typedef typename Conditional<
        static_cast(GetSize::value) 
            <= static_cast(position),
        AppendItem,
        Identity>::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
struct TuringMachine {
    typedef Input input;
    typedef Transitions transitions;
    typedef StartState start_state;

    typedef Controller, Transitions> controller;
    typedef typename controller::end_config end_config;
    typedef typename controller::end_input end_input;
    typedef typename controller::end_state end_state;
    enum { end_position = controller::end_position };
};

#include 

template<>
char const* Input<-1>::name = "_";

char const* QAccept::name = "qaccept";
char const* QReject::name = "qreject";

int main() {
    DEF_INPUT(1, x);
    DEF_INPUT(2, x_mark);
    DEF_INPUT(3, split);

    DEF_STATE(0, start);
    DEF_STATE(1, find_blank);
    DEF_STATE(2, go_back);

    /* syntax:  State, Input, NewState, Output, Move */
    typedef TypeList< 
        Rule,
        Rule,
        Rule,
        Rule,
        Rule,
        Rule,
        Rule,
        Rule> rules;

    /* syntax: initial input, rules, start state */
    typedef TuringMachine, rules, start> double_it;
    static_assert(IsSame>::value, 
                "Hmm... This is borky!");
}

<답변3>

"C ++ Templates Are Turing Complete"는 템플릿에서 Turing 머신의 구현을 제공합니다. 이는 사소하지 않고 매우 직접적인 방식으로 요점을 증명합니다. 물론 그다지 유용하지도 않습니다!


<답변4>

내 C ++는 약간 녹슬 어서 완벽하지는 않지만 거의 비슷합니다.

template  struct Factorial
{
    enum { val = Factorial::val * N };
};

template <> struct Factorial<0>
{
    enum { val = 1 };
}

const int num = Factorial<10>::val;    // num set to 10! at compile time.

요점은 컴파일러가 대답에 도달 할 때까지 재귀 정의를 완전히 평가하고 있음을 보여주는 것입니다.


<답변5>

사소하지 않은 예제를 제공하려면 : http://gitorious.org/metatrace, C ++ 컴파일 타임 레이 트레이서.

C ++ 0x는 constexpr 형식으로 비 템플릿, 컴파일 타임, 튜링 완료 기능을 추가합니다.

constexpr unsigned int fac (unsigned int u) {
        return (u<=1) ? (1) : (u*fac(u-1));
}

컴파일 시간 상수가 필요한 모든 곳에서 constexpr-expression을 사용할 수 있지만 상수가 아닌 매개 변수로 constexpr-functions를 호출 할 수도 있습니다.

한 가지 멋진 점은 컴파일 시간 부동 소수점 산술이 런타임 부동 소수점 산술과 일치 할 필요가 없다고 표준에 명시 적으로 명시되어 있지만 이것이 마침내 컴파일 시간 부동 소수점 연산을 활성화한다는 것입니다.

bool f () {문자 배열 [1 + int (1 + 0.2-0.1-0.1)]; // 변환 중에 평가해야합니다. int size = 1 + int (1 + 0.2-0.1-0.1); // 런타임에 평가 될 수 있음 return sizeof (array) == size; } f ()의 값이 참인지 거짓인지는 지정되지 않습니다.


<답변6>

The Book Modern C ++ Design-Generic Programming and Design Pattern by Andrei Alexandrescu는 유용하고 강력한 제네릭 프로그래밍 패턴을 경험할 수있는 최고의 장소입니다.


<답변7>

팩토리얼 예제는 실제로 템플릿이 Primitive Recursion을 지원한다는 것을 보여주는만큼 튜링이 완전하다는 것을 보여주지 않습니다. 템플릿이 완전하다는 것을 보여주는 가장 쉬운 방법은 Church-Turing 논문을 사용하는 것입니다. 즉, Turing 머신 (지저분하고 약간 무의미 함) 또는 형식화되지 않은 람다 미적분의 세 가지 규칙 (앱, abs var)을 구현하는 것입니다. 후자는 훨씬 간단하고 훨씬 흥미 롭습니다.

논의중인 것은 C ++ 템플릿이 컴파일 타임에 순수 함수형 프로그래밍을 허용한다는 것을 이해할 때 매우 유용한 기능입니다. 이는 표현력이 풍부하고 강력하며 우아하지만 경험이 거의없는 경우 작성하기 매우 복잡한 형식주의입니다. 또한 얼마나 많은 사람들이 템플릿 화가 심한 코드를 얻는 데 종종 큰 노력이 필요할 수 있다는 사실을 알아 차리십시오. 이것은 정확히 (순수한) 함수 언어의 경우입니다. 이것은 컴파일을 더 어렵게하지만 놀랍게도 디버깅이 필요없는 코드를 생성합니다.


<답변8>

템플릿 메타 프로그래밍이라고 생각합니다.


<답변9>

음, 여기에 4- 상태 2- 기호 바쁜 비버를 실행하는 컴파일 타임 Turing Machine 구현이 있습니다.

#include 

#pragma mark - Tape

constexpr int Blank = -1;

template
class Tape {
public:
    using type = Tape;
    constexpr static int length = sizeof...(xs);
};

#pragma mark - Print

template
void print(T);

template<>
void print(Tape<>) {
    std::cout << std::endl;
}

template
void print(Tape) {
    if (x == Blank) {
        std::cout << "_ ";
    } else {
        std::cout << x << " ";
    }
    print(Tape());
}

#pragma mark - Concatenate

template
class Concatenate;

template
class Concatenate, Tape> {
public:
    using type = Tape;
};

#pragma mark - Invert

template
class Invert;

template<>
class Invert> {
public:
    using type = Tape<>;
};

template
class Invert> {
public:
    using type = typename Concatenate<
        typename Invert>::type,
        Tape
    >::type;
};

#pragma mark - Read

template
class Read;

template
class Read> {
public:
    using type = typename std::conditional<
        (n == 0),
        std::integral_constant,
        Read>
    >::type::type;
};

#pragma mark - N first and N last

template
class NLast;

template
class NLast> {
public:
    using type = typename std::conditional<
        (n == sizeof...(xs)),
        Tape,
        NLast>
    >::type::type;
};

template
class NFirst;

template
class NFirst> {
public:
    using type = typename Invert<
        typename NLast<
            n, typename Invert>::type
        >::type
    >::type;
};

#pragma mark - Write

template
class Write;

template
class Write> {
public:
    using type = typename Concatenate<
        typename Concatenate<
            typename NFirst>::type,
            Tape
        >::type,
        typename NLast<(sizeof...(xs) - pos - 1), Tape>::type
    >::type;
};

#pragma mark - Move

template
class Hold;

template
class Hold> {
public:
    constexpr static int position = pos;
    using tape = Tape;
};

template
class Left;

template
class Left> {
public:
    constexpr static int position = typename std::conditional<
        (pos > 0),
        std::integral_constant,
        std::integral_constant
    >::type();

    using tape = typename std::conditional<
        (pos > 0),
        Tape,
        Tape
    >::type;
};

template
class Right;

template
class Right> {
public:
    constexpr static int position = pos + 1;

    using tape = typename std::conditional<
        (pos < sizeof...(xs) - 1),
        Tape,
        Tape
    >::type;
};

#pragma mark - States

template 
class Stop {
public:
    constexpr static int write = -1;
    template using move = Hold;
    template using next = Stop;
};

#define ADD_STATE(_state_)      \
template                   \
class _state_ { };

#define ADD_RULE(_state_, _read_, _write_, _move_, _next_)          \
template<>                                                          \
class _state_<_read_> {                                             \
public:                                                             \
    constexpr static int write = _write_;                           \
    template using move = _move_;   \
    template using next = _next_;                         \
};

#pragma mark - Machine

template class, int, class>
class Machine;

template class State, int pos, int... xs>
class Machine> {
    constexpr static int symbol = typename Read>::type();
    using state = State;

    template
    using nextState = typename State::template next;

    using modifiedTape = typename Write>::type;
    using move = typename state::template move;

    constexpr static int nextPos = move::position;
    using nextTape = typename move::tape;

public:
    using step = Machine;
};

#pragma mark - Run

template
class Run;

template class State, int pos, int... xs>
class Run>> {
    using step = typename Machine>::step;

public:
    using type = typename std::conditional<
        std::is_same, Stop<0>>::value,
        Tape,
        Run
    >::type::type;
};

ADD_STATE(A);
ADD_STATE(B);
ADD_STATE(C);
ADD_STATE(D);

ADD_RULE(A, Blank, 1, Right, B);
ADD_RULE(A, 1, 1, Left, B);

ADD_RULE(B, Blank, 1, Left, A);
ADD_RULE(B, 1, Blank, Left, C);

ADD_RULE(C, Blank, 1, Right, Stop);
ADD_RULE(C, 1, 1, Left, D);

ADD_RULE(D, Blank, 1, Right, D);
ADD_RULE(D, 1, Blank, Right, A);

using tape = Tape;
using machine = Machine;
using result = Run::type;

int main() {
    print(result());
    return 0;
}

Ideone 증명 실행 : https://ideone.com/MvBU3Z

설명 : http://victorkomarov.blogspot.ru/2016/03/compile-time-turing-machine.html

더 많은 예제가있는 Github : https://github.com/fnz/CTTM


<답변10>

FFT 구현에 대한 Dr. Dobbs의이 기사를 내가 그렇게 사소하지 않다고 생각하는 템플릿으로 확인할 수 있습니다. 요점은 FFT 알고리즘이 많은 상수 (예 : sin 테이블)를 사용하므로 컴파일러가 템플릿이 아닌 구현보다 더 나은 최적화를 수행 할 수 있도록하는 것입니다.

파트 I

파트 II


<답변11>

디버그가 거의 불가능하지만 순전히 기능적인 언어라는 점을 지적하는 것도 재미 있습니다. James post를 보면 그것이 기능적이라는 것을 알 수 있습니다. 일반적으로 C ++의 가장 유용한 기능은 아닙니다. 이를 수행하도록 설계되지 않았습니다. 발견 된 것입니다.


<답변12>

적어도 이론적으로는 컴파일 타임에 상수를 계산하려는 경우 유용 할 수 있습니다. 템플릿 메타 프로그래밍을 확인하세요.


<답변13>

합리적으로 유용한 예는 비율 클래스입니다. 주위에 떠 다니는 몇 가지 변종이 있습니다. D == 0 케이스를 잡는 것은 부분적인 과부하로 매우 간단합니다. 실제 계산은 N과 D의 GCD와 컴파일 시간을 계산하는 것입니다. 이것은 컴파일 타임 계산에서 이러한 비율을 사용할 때 필수적입니다.

예 : 센티미터 (5) * 킬로미터 (5)를 계산할 때 컴파일 타임에 ratio <1,100> 및 ratio <1000,1>을 곱하게됩니다. 오버플로를 방지하려면 ratio <1000,100> 대신 ratio <10,1>을 원합니다.


<답변14>

튜링 머신은 튜링이 완벽하지만, 그렇다고 프로덕션 코드에 하나를 사용해야한다는 의미는 아닙니다.

템플릿으로 사소하지 않은 것을 시도하는 것은 내 경험에 지저분하고 추하고 무의미합니다. "코드"를 "디버그"할 수있는 방법이 없습니다. 컴파일 시간 오류 메시지는 모호하고 일반적으로 가능성이 가장 낮은 위치에 있으며 다른 방법으로 동일한 성능 이점을 얻을 수 있습니다. (힌트 : 4! = 24). 더 나쁜 것은 여러분의 코드가 일반 C ++ 프로그래머가 이해할 수 없으며 현재 컴파일러 내에서 광범위한 지원 수준으로 인해 이식이 불가능할 가능성이 있다는 것입니다.

템플릿은 일반적인 코드 생성 (컨테이너 클래스, 클래스 래퍼, 믹스 인)에 적합하지만, 제 생각에는 템플릿의 튜링 완전성은 실제로 유용하지 않습니다.


<답변15>

프로그래밍하지 않는 방법의 또 다른 예 :


template
struct K17 {
    static const int x =
    K17  >::x
    + K17  >::x
    + K17  >::x
    + K17  >::x
    + K17  >::x;
};
template 
struct K17 <16,A,B> { static const int x = 1; };
static const int z = K17 <0,0,int>::x;
void main(void) { }

C ++ 템플릿에 게시가 완료되었습니다.

반응형