SlideShare uma empresa Scribd logo
1 de 25
Baixar para ler offline
Preprocessor programming
2013. 08. 23.
최재영
Motivation
• Don’t Repeat Yourself!
2
template <class T>
DoAsync(void (T::*member)()) {}
template <class T, class A1>
DoAsync(void (T::*member)(), A1 a1) {}
template <class T, class A1, class A2>
DoAsync(void (T::*member)(), A1 a1, A2 a2) {}
template <class T, class A1, class A2, class A3>
DoAsync(void (T::*member)(), A1 a1, A2 a2, A3 a3) {}
template <class T, class A1, class A2, class A3, class A4>
DoAsync(void (T::*member)(), A1 a1, A2 a2, A3 a3, A4 a4) {}
enum SomeType {
TypeA,
TypeB,
};
const TCHAR* GetSomeTypeName(SomeType type) {
if (type == TypeA) return _T("TypeA");
if (type == TypeB) return _T("TypeB");
return _T("");
}
Why?
• generate code that cannot be generated by template
• or generate boilerplate template code
3
concat
token
repetition
multi-pass
generation
a ## b
#include "repl_a.h"
#include "spec.h"
#include "repl_b.h"
#include "spec.h"
#define TARGET "spec.h"
#include "iteration.h"
#define DECL(name) 
template <REPEAT(MAX_SIZE, class T)>
흐름
4
X-Macro
repetition
Boost PP
horizontal
vertical
Fundamentals
5
// object-like macro
#define <identifier> <replacement token list>
// function-like macro, note parameters
#define <identifier>(<parameter list>) <replacement token list>
// local macro
#define <identifier>
/* do something */
#undef <identifier>
• Macro expansion in the preprocessor is entirely functional.
But the preprocessor disallows recursion.
Fundamentals (cont.)
6
// reentrancy problem
#define CONCAT(a, b) a ## b
#define AB(x, y) CONCAT(x, y)
CONCAT(A, B(p, q)) // CONCAT(p, q), not pq
// solving the one-depth reentrancy problem
#define CONCAT2(a, b) a ## b
#define AB(x, y) CONCAT(x, y)
#define CONCAT(a, b) CONCAT2(a, b)
CONCAT(A, B(p, q)) // pq
• How many recursion-depth does it support?
• How many case does it define?
X-Macro
• generating repeating code structures at compile time
7
enum SomeType {
ST_SOME,
ST_OTHER
};
inline const TCHAR* GetNameFromSomeType(SomeType type) {
if (type == ST_SOME) return _T("ST_SOME");
if (type == ST_OTHER) return _T("ST_OTHER");
return _T("");
}
inline SomeType GetSomeTypeFromName(const TCHAR* str) {
if (_tcsicmp(str, _T("ST_SOME") == 0) return ST_SOME;
if (_tcsicmp(str, _T("ST_OTHER") == 0) return ST_OTHER;
return static_cast<SomeType>(-1);
}
X-Macro (cont.)
8
ENUM_BEGIN(SomeType)
ENUM(ST_SOME)
ENUM(ST_OTHER)
ENUM_END(SomeType)
#define ENUM_BEGIN(name) enum name {
#define ENUM(name) name,
#define ENUM_END(name) };
#define ENUM_BEGIN(name) 
inline const TCHAR* GetNameFrom##name##(name type) {
#define ENUM(name) if (type == name) return _T(#name);
#define ENUM_END(name) return _T(""); }
#define ENUM_BEGIN(name) 
inline name Get##name##FromName(const TCHAR* str) {
#define ENUM(name) if (_tcsicmp(str, #name) == 0) return name;
#define ENUM_END(name) return static_cast<name>(-1); }
sometype_spec.h
enum_decl_gen.h
enum_to_str_gen.h
str_to_enum_gen.h
X-Macro (cont.)
9
#include "enum_decl_gen.h"
#include "sometype_spec.h"
enums.h
#include "enum_to_str_gen.h"
#include "sometype_spec.h"
#include "enum_gen_reset.h"
#include "str_to_enum_gen.h"
#include "sometype_spec.h"
enums.cpp
#undef ENUM_BEGIN
#undef ENUM
#undef ENUM_END
enum_gen_reset.h
Repetition
• horizontal repetition
• vertical repetition
10
template <class T>
void DoAsync(...);
template <class T, class A0>
void DoAsync(...);
template <class T, class A0, class A1>
void DoAsync(...);
template <class T, class A0, class A1, class A2>
void DoAsync(...);
template <class T, class A0, class A1, class A2, class A3>
void DoAsync(...);
vertical
horizontal
Horizontal Repetition (cont.)
• the preprocessor disallows recursion.
• all cases should be defined.
11
#define REPEAT_1(m) m(0)
#define REPEAT_2(m) REPEAT_1(m), m(1)
#define REPEAT_3(m) REPEAT_2(m), m(2)
#define REPEAT_4(m) REPEAT_3(m), m(3)
#define REPEAT_5(m) REPEAT_4(m), m(4)
// ...
#define REPEAT(c, m) CONCAT(REPEAT_, c)(m)
chaining
end condition
case selector
Horizontal Repetition (cont.)
12
generator#define REPEAT_PARAM(n) class T ## n
template <class R, REPEAT(4, REPEAT_PARAM)>
struct test_t {}; repeat count
template <class R, class T0, class T1, class T2, class T3>
struct test_t {}; repeated
expand!
Vertical Repetition (cont.)
• macro state & self-include
13
#if !defined(CURRENT)
# define CURRENT 0
# include "repeater.h"
#elif CURRENT < SIZE
# if CURRENT == 0
# undef CURRENT
# define CURRENT 1
# elif CURRENT == 1
# undef CURRENT
# define CURRENT 2
// ...
# endif
# include TARGET
# include "repeater.h"
#else
#endif
repeater.h
define initial state
self-include
self-include
target-include
state-machine
repeater.h(TARGET, SIZE)
#ifndef REPEAT_PARAM
#define REPEAT_PARAM(n) class T ## n
#endif
template <class R, REPEAT(CURRENT, REPEAT_PARAM)>
struct test_t {};
Vertical Repetition (cont.)
14
spec.h
iteration count
#define TARGET "spec.h"
#define SIZE 3
#include "repeater.h"
main.cpp
set macro parameter
call macro file function
Is it end?
15
template <class T0, class T1, class T2>
struct tiny_size {};
template <class T0, class T1>
struct tiny_size<T0, T1, none> {};
template <class T0>
struct tiny_size<T0, none, none> {};
template <>
struct tiny_size<none, none, none> {};
comma problem
need to sub function
seperate original template & partial specialization generator
COMMA_IF_NONZERO (helper)
16
#define COMMA_IF_NONZERO_0
#define COMMA_IF_NONZERO_1 ,
#define COMMA_IF_NONZERO_2 ,
#define COMMA_IF_NONZERO_3 ,
#define COMMA_IF_NONZERO_4 ,
#define COMMA_IF_NONZERO_5 ,
#define COMMA_IF_NONZERO(n) CONCAT(COMMA_IF_NONZERO_, n)
all cases should be defined!
SUB (helper)
17
// ...
#define SUB_33 0
#define SUB_20 2
#define SUB_21 1
#define SUB_22 0
#define SUB_10 1
#define SUB_11 0
#define SUB_00 0
#define SUB(a, b) CONCAT(CONCAT(SUB_, a), b)
all cases should be defined ... ?
Vertical Repetition (cont.)
• size ≠ limit
18
// ...
#elif CURRENT < LIMIT
# if CURRENT == 0
# undef CURRENT
# define CURRENT 1
// ...
repeater.h
repeater.h(TARGET, SIZE, LIMIT)
Vertical Repetition (cont.)
19
main.cpp
#define SIZE 3
template <class R
COMMA_IF_NONZERO(SIZE)
REPEAT(SIZE, REPEAT_PARAM)>
struct test
{};
#define TARGET "spec.h"
#define LIMIT SUB(SIZE, 1)
#include "repeater.h"
template <class R
COMMA_IF_NONZERO(CURRENT)
REPEAT(CURRENT, REPEAT_PARAM)>
struct test<R
COMMA_IF_NONZERO(CURRENT)
REPEAT(CURRENT, REPEAT_VAR)
COMMA_IF_NONZERO(SUB(SIZE, CURRENT))
REPEAT(SUB(SIZE, CURRENT), REPEAT_NONE)>
{};
spec.h
file iteration
generate partial specialization
generate original template
Vertical Repetition (cont.)
20
• Local iteration: using macro state
#if !defined(IS_REPEATING)
# define IS_REPEATING 1
# include "repeater.h"
#else
# if !defined(CURRENT)
# define CURRENT 0
# include "repeater.h"
# elif CURRENT <= LIMIT
// ...
# else
# undef IS_REPEATING
# endif
#endif
initial state
iterating state
Vertical Repetition (cont.)
21
#if !defined(IS_REPEATING)
# define SIZE 3
template <class R
COMMA_IF_NONZERO(SIZE)
REPEAT(CURRENT, REPEAT_PARAM)>
struct test {};
# define TARGET "test.h"
# define LIMIT SUB(SIZE, 1)
# include "repeater.h"
#else
template <class R
COMMA_IF_NONZERO(CURRENT)
REPEAT(CURRENT, REPEAT_PARAM)>
struct test<R
COMMA_IF_NONZERO(CURRENT)
REPEAT(CURRENT, REPEAT_VAR)
COMMA_IF_NONZERO(SUB(SIZE, CURRENT))
REPEAT(SUB(SIZE, CURRENT), REPEAT_NONE)> {};
#endif
iterating state
initial state
repetition entry-point
boost pp
• boost preprocess library
– BOOST_PP_CAT
– BOOST_PP_ENUM_PARAMS
– BOOST_PP_REPEAT
– BOOST_PP_COMMA_IF
– BOOST_PP_SUB
– BOOST_PP_DEC
– BOOST_PP_WHILE
– BOOST_PP_ITERATE
22
boost pp (cont.)
• many predefined macros functions
– Arithmetic, Logical, and Comparison Operations
– Control Structures
– Token Pasting(argument selection)
– Data Types(sequence, tuple, array, list)
• well-optimized expand complexity
23
# define BOOST_PP_NODE_ENTRY_256(p) 
BOOST_PP_NODE_128(p)(p)(p)(p)(p)(p)(p)(p)
# define BOOST_PP_NODE_ENTRY_128(p) 
BOOST_PP_NODE_64(p)(p)(p)(p)(p)(p)(p)
// ...
# define BOOST_PP_NODE_ENTRY_2(p) BOOST_PP_NODE_1(p)
boost pp (cont.)
• supports 256 reentrancy
• supports 3 dimension (concurrently expandable count)
24
# define BOOST_PP_DEC_0 0
# define BOOST_PP_DEC_1 0
// ...
# define BOOST_PP_DEC_255 254
# define BOOST_PP_DEC_256 255
# define BOOST_PP_REPEAT_1(c, m, d) BOOST_PP_REPEAT_1_I(c, m, d)
# define BOOST_PP_REPEAT_2(c, m, d) BOOST_PP_REPEAT_2_I(c, m, d)
# define BOOST_PP_REPEAT_3(c, m, d) BOOST_PP_REPEAT_3_I(c, m, d)
Summary
• Don't repeat yourself!
• reduce boilerplate code using preprocess programming
• but, your compile time is also boosted!
25

Mais conteúdo relacionado

Mais procurados

Input output functions
Input output functionsInput output functions
Input output functions
hyderali123
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
Amit Kapoor
 

Mais procurados (20)

An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
 
C Programming Language Part 8
C Programming Language Part 8C Programming Language Part 8
C Programming Language Part 8
 
C tech questions
C tech questionsC tech questions
C tech questions
 
Core c sharp and .net quick reference
Core c sharp and .net quick referenceCore c sharp and .net quick reference
Core c sharp and .net quick reference
 
Paradigmas de Linguagens de Programacao - Aula #5
Paradigmas de Linguagens de Programacao - Aula #5Paradigmas de Linguagens de Programacao - Aula #5
Paradigmas de Linguagens de Programacao - Aula #5
 
C Programming Language Part 9
C Programming Language Part 9C Programming Language Part 9
C Programming Language Part 9
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
 
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
 
c programming
c programmingc programming
c programming
 
Input output functions
Input output functionsInput output functions
Input output functions
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
 
C reference card
C reference cardC reference card
C reference card
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
 
C Reference Card (Ansi) 2
C Reference Card (Ansi) 2C Reference Card (Ansi) 2
C Reference Card (Ansi) 2
 
ANSI C REFERENCE CARD
ANSI C REFERENCE CARDANSI C REFERENCE CARD
ANSI C REFERENCE CARD
 
Unit 3
Unit 3 Unit 3
Unit 3
 
C Structure and Union in C
C Structure and Union in CC Structure and Union in C
C Structure and Union in C
 
C Programming Language Part 6
C Programming Language Part 6C Programming Language Part 6
C Programming Language Part 6
 
Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
 

Destaque

NDC 2011, C++ 프로그래머를 위한 C#
NDC 2011, C++ 프로그래머를 위한 C#NDC 2011, C++ 프로그래머를 위한 C#
NDC 2011, C++ 프로그래머를 위한 C#
tcaesvk
 
공성대전 C# 사용기
공성대전 C# 사용기공성대전 C# 사용기
공성대전 C# 사용기
Myoung-gyu Gang
 
NDC 2014, 피할 수 없는 문자열의 세계
NDC 2014, 피할 수 없는 문자열의 세계NDC 2014, 피할 수 없는 문자열의 세계
NDC 2014, 피할 수 없는 문자열의 세계
tcaesvk
 
헤테로지니어스 컴퓨팅 : CPU 에서 GPU 로 옮겨가기
헤테로지니어스 컴퓨팅 :  CPU 에서 GPU 로 옮겨가기헤테로지니어스 컴퓨팅 :  CPU 에서 GPU 로 옮겨가기
헤테로지니어스 컴퓨팅 : CPU 에서 GPU 로 옮겨가기
zupet
 

Destaque (15)

Index Analysis
Index AnalysisIndex Analysis
Index Analysis
 
AWS GameServer Management
AWS GameServer ManagementAWS GameServer Management
AWS GameServer Management
 
C# Game Server
C# Game ServerC# Game Server
C# Game Server
 
NDC 2011, C++ 프로그래머를 위한 C#
NDC 2011, C++ 프로그래머를 위한 C#NDC 2011, C++ 프로그래머를 위한 C#
NDC 2011, C++ 프로그래머를 위한 C#
 
NDC12_Lockless게임서버설계와구현
NDC12_Lockless게임서버설계와구현NDC12_Lockless게임서버설계와구현
NDC12_Lockless게임서버설계와구현
 
공성대전 C# 사용기
공성대전 C# 사용기공성대전 C# 사용기
공성대전 C# 사용기
 
Iocp 기본 구조 이해
Iocp 기본 구조 이해Iocp 기본 구조 이해
Iocp 기본 구조 이해
 
NDC 2014, 피할 수 없는 문자열의 세계
NDC 2014, 피할 수 없는 문자열의 세계NDC 2014, 피할 수 없는 문자열의 세계
NDC 2014, 피할 수 없는 문자열의 세계
 
게임서버프로그래밍 #6 - 예외처리 및 로깅
게임서버프로그래밍 #6 - 예외처리 및 로깅게임서버프로그래밍 #6 - 예외처리 및 로깅
게임서버프로그래밍 #6 - 예외처리 및 로깅
 
게임서버프로그래밍 #3 - 메모리 및 오브젝트 풀링
게임서버프로그래밍 #3 - 메모리 및 오브젝트 풀링게임서버프로그래밍 #3 - 메모리 및 오브젝트 풀링
게임서버프로그래밍 #3 - 메모리 및 오브젝트 풀링
 
게임서버프로그래밍 #4 - 멀티스레드 프로그래밍
게임서버프로그래밍 #4 - 멀티스레드 프로그래밍게임서버프로그래밍 #4 - 멀티스레드 프로그래밍
게임서버프로그래밍 #4 - 멀티스레드 프로그래밍
 
게임서버프로그래밍 #0 - TCP 및 이벤트 통지모델
게임서버프로그래밍 #0 - TCP 및 이벤트 통지모델게임서버프로그래밍 #0 - TCP 및 이벤트 통지모델
게임서버프로그래밍 #0 - TCP 및 이벤트 통지모델
 
게임서버프로그래밍 #7 - 패킷핸들링 및 암호화
게임서버프로그래밍 #7 - 패킷핸들링 및 암호화게임서버프로그래밍 #7 - 패킷핸들링 및 암호화
게임서버프로그래밍 #7 - 패킷핸들링 및 암호화
 
사설 서버를 막는 방법들 (프리섭, 더이상은 Naver)
사설 서버를 막는 방법들 (프리섭, 더이상은 Naver)사설 서버를 막는 방법들 (프리섭, 더이상은 Naver)
사설 서버를 막는 방법들 (프리섭, 더이상은 Naver)
 
헤테로지니어스 컴퓨팅 : CPU 에서 GPU 로 옮겨가기
헤테로지니어스 컴퓨팅 :  CPU 에서 GPU 로 옮겨가기헤테로지니어스 컴퓨팅 :  CPU 에서 GPU 로 옮겨가기
헤테로지니어스 컴퓨팅 : CPU 에서 GPU 로 옮겨가기
 

Semelhante a Preprocessor Programming

lab03build.bat@echo offclsset DRIVE_LETTER=1set.docx
lab03build.bat@echo offclsset DRIVE_LETTER=1set.docxlab03build.bat@echo offclsset DRIVE_LETTER=1set.docx
lab03build.bat@echo offclsset DRIVE_LETTER=1set.docx
DIPESH30
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
JawadTanvir
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
ssuser3cbb4c
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
Tech_MX
 
Intermediate code generation1
Intermediate code generation1Intermediate code generation1
Intermediate code generation1
Shashwat Shriparv
 
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docxlab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
DIPESH30
 
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
Little Tukta Lita
 

Semelhante a Preprocessor Programming (20)

Python crush course
Python crush coursePython crush course
Python crush course
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
 
lab03build.bat@echo offclsset DRIVE_LETTER=1set.docx
lab03build.bat@echo offclsset DRIVE_LETTER=1set.docxlab03build.bat@echo offclsset DRIVE_LETTER=1set.docx
lab03build.bat@echo offclsset DRIVE_LETTER=1set.docx
 
Best C++ Programming Homework Help
Best C++ Programming Homework HelpBest C++ Programming Homework Help
Best C++ Programming Homework Help
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
Tut1
Tut1Tut1
Tut1
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
 
Статичный SQL в С++14. Евгений Захаров ➠ CoreHard Autumn 2019
Статичный SQL в С++14. Евгений Захаров ➠  CoreHard Autumn 2019Статичный SQL в С++14. Евгений Захаров ➠  CoreHard Autumn 2019
Статичный SQL в С++14. Евгений Захаров ➠ CoreHard Autumn 2019
 
Intermediate code generation1
Intermediate code generation1Intermediate code generation1
Intermediate code generation1
 
Software Construction Assignment Help
Software Construction Assignment HelpSoftware Construction Assignment Help
Software Construction Assignment Help
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
Ch8a
Ch8aCh8a
Ch8a
 
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docxlab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
 
Unit 2
Unit 2Unit 2
Unit 2
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
 

Último

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 

Último (20)

Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 

Preprocessor Programming

  • 2. Motivation • Don’t Repeat Yourself! 2 template <class T> DoAsync(void (T::*member)()) {} template <class T, class A1> DoAsync(void (T::*member)(), A1 a1) {} template <class T, class A1, class A2> DoAsync(void (T::*member)(), A1 a1, A2 a2) {} template <class T, class A1, class A2, class A3> DoAsync(void (T::*member)(), A1 a1, A2 a2, A3 a3) {} template <class T, class A1, class A2, class A3, class A4> DoAsync(void (T::*member)(), A1 a1, A2 a2, A3 a3, A4 a4) {} enum SomeType { TypeA, TypeB, }; const TCHAR* GetSomeTypeName(SomeType type) { if (type == TypeA) return _T("TypeA"); if (type == TypeB) return _T("TypeB"); return _T(""); }
  • 3. Why? • generate code that cannot be generated by template • or generate boilerplate template code 3 concat token repetition multi-pass generation a ## b #include "repl_a.h" #include "spec.h" #include "repl_b.h" #include "spec.h" #define TARGET "spec.h" #include "iteration.h" #define DECL(name) template <REPEAT(MAX_SIZE, class T)>
  • 5. Fundamentals 5 // object-like macro #define <identifier> <replacement token list> // function-like macro, note parameters #define <identifier>(<parameter list>) <replacement token list> // local macro #define <identifier> /* do something */ #undef <identifier> • Macro expansion in the preprocessor is entirely functional. But the preprocessor disallows recursion.
  • 6. Fundamentals (cont.) 6 // reentrancy problem #define CONCAT(a, b) a ## b #define AB(x, y) CONCAT(x, y) CONCAT(A, B(p, q)) // CONCAT(p, q), not pq // solving the one-depth reentrancy problem #define CONCAT2(a, b) a ## b #define AB(x, y) CONCAT(x, y) #define CONCAT(a, b) CONCAT2(a, b) CONCAT(A, B(p, q)) // pq • How many recursion-depth does it support? • How many case does it define?
  • 7. X-Macro • generating repeating code structures at compile time 7 enum SomeType { ST_SOME, ST_OTHER }; inline const TCHAR* GetNameFromSomeType(SomeType type) { if (type == ST_SOME) return _T("ST_SOME"); if (type == ST_OTHER) return _T("ST_OTHER"); return _T(""); } inline SomeType GetSomeTypeFromName(const TCHAR* str) { if (_tcsicmp(str, _T("ST_SOME") == 0) return ST_SOME; if (_tcsicmp(str, _T("ST_OTHER") == 0) return ST_OTHER; return static_cast<SomeType>(-1); }
  • 8. X-Macro (cont.) 8 ENUM_BEGIN(SomeType) ENUM(ST_SOME) ENUM(ST_OTHER) ENUM_END(SomeType) #define ENUM_BEGIN(name) enum name { #define ENUM(name) name, #define ENUM_END(name) }; #define ENUM_BEGIN(name) inline const TCHAR* GetNameFrom##name##(name type) { #define ENUM(name) if (type == name) return _T(#name); #define ENUM_END(name) return _T(""); } #define ENUM_BEGIN(name) inline name Get##name##FromName(const TCHAR* str) { #define ENUM(name) if (_tcsicmp(str, #name) == 0) return name; #define ENUM_END(name) return static_cast<name>(-1); } sometype_spec.h enum_decl_gen.h enum_to_str_gen.h str_to_enum_gen.h
  • 9. X-Macro (cont.) 9 #include "enum_decl_gen.h" #include "sometype_spec.h" enums.h #include "enum_to_str_gen.h" #include "sometype_spec.h" #include "enum_gen_reset.h" #include "str_to_enum_gen.h" #include "sometype_spec.h" enums.cpp #undef ENUM_BEGIN #undef ENUM #undef ENUM_END enum_gen_reset.h
  • 10. Repetition • horizontal repetition • vertical repetition 10 template <class T> void DoAsync(...); template <class T, class A0> void DoAsync(...); template <class T, class A0, class A1> void DoAsync(...); template <class T, class A0, class A1, class A2> void DoAsync(...); template <class T, class A0, class A1, class A2, class A3> void DoAsync(...); vertical horizontal
  • 11. Horizontal Repetition (cont.) • the preprocessor disallows recursion. • all cases should be defined. 11 #define REPEAT_1(m) m(0) #define REPEAT_2(m) REPEAT_1(m), m(1) #define REPEAT_3(m) REPEAT_2(m), m(2) #define REPEAT_4(m) REPEAT_3(m), m(3) #define REPEAT_5(m) REPEAT_4(m), m(4) // ... #define REPEAT(c, m) CONCAT(REPEAT_, c)(m) chaining end condition case selector
  • 12. Horizontal Repetition (cont.) 12 generator#define REPEAT_PARAM(n) class T ## n template <class R, REPEAT(4, REPEAT_PARAM)> struct test_t {}; repeat count template <class R, class T0, class T1, class T2, class T3> struct test_t {}; repeated expand!
  • 13. Vertical Repetition (cont.) • macro state & self-include 13 #if !defined(CURRENT) # define CURRENT 0 # include "repeater.h" #elif CURRENT < SIZE # if CURRENT == 0 # undef CURRENT # define CURRENT 1 # elif CURRENT == 1 # undef CURRENT # define CURRENT 2 // ... # endif # include TARGET # include "repeater.h" #else #endif repeater.h define initial state self-include self-include target-include state-machine repeater.h(TARGET, SIZE)
  • 14. #ifndef REPEAT_PARAM #define REPEAT_PARAM(n) class T ## n #endif template <class R, REPEAT(CURRENT, REPEAT_PARAM)> struct test_t {}; Vertical Repetition (cont.) 14 spec.h iteration count #define TARGET "spec.h" #define SIZE 3 #include "repeater.h" main.cpp set macro parameter call macro file function
  • 15. Is it end? 15 template <class T0, class T1, class T2> struct tiny_size {}; template <class T0, class T1> struct tiny_size<T0, T1, none> {}; template <class T0> struct tiny_size<T0, none, none> {}; template <> struct tiny_size<none, none, none> {}; comma problem need to sub function seperate original template & partial specialization generator
  • 16. COMMA_IF_NONZERO (helper) 16 #define COMMA_IF_NONZERO_0 #define COMMA_IF_NONZERO_1 , #define COMMA_IF_NONZERO_2 , #define COMMA_IF_NONZERO_3 , #define COMMA_IF_NONZERO_4 , #define COMMA_IF_NONZERO_5 , #define COMMA_IF_NONZERO(n) CONCAT(COMMA_IF_NONZERO_, n) all cases should be defined!
  • 17. SUB (helper) 17 // ... #define SUB_33 0 #define SUB_20 2 #define SUB_21 1 #define SUB_22 0 #define SUB_10 1 #define SUB_11 0 #define SUB_00 0 #define SUB(a, b) CONCAT(CONCAT(SUB_, a), b) all cases should be defined ... ?
  • 18. Vertical Repetition (cont.) • size ≠ limit 18 // ... #elif CURRENT < LIMIT # if CURRENT == 0 # undef CURRENT # define CURRENT 1 // ... repeater.h repeater.h(TARGET, SIZE, LIMIT)
  • 19. Vertical Repetition (cont.) 19 main.cpp #define SIZE 3 template <class R COMMA_IF_NONZERO(SIZE) REPEAT(SIZE, REPEAT_PARAM)> struct test {}; #define TARGET "spec.h" #define LIMIT SUB(SIZE, 1) #include "repeater.h" template <class R COMMA_IF_NONZERO(CURRENT) REPEAT(CURRENT, REPEAT_PARAM)> struct test<R COMMA_IF_NONZERO(CURRENT) REPEAT(CURRENT, REPEAT_VAR) COMMA_IF_NONZERO(SUB(SIZE, CURRENT)) REPEAT(SUB(SIZE, CURRENT), REPEAT_NONE)> {}; spec.h file iteration generate partial specialization generate original template
  • 20. Vertical Repetition (cont.) 20 • Local iteration: using macro state #if !defined(IS_REPEATING) # define IS_REPEATING 1 # include "repeater.h" #else # if !defined(CURRENT) # define CURRENT 0 # include "repeater.h" # elif CURRENT <= LIMIT // ... # else # undef IS_REPEATING # endif #endif initial state iterating state
  • 21. Vertical Repetition (cont.) 21 #if !defined(IS_REPEATING) # define SIZE 3 template <class R COMMA_IF_NONZERO(SIZE) REPEAT(CURRENT, REPEAT_PARAM)> struct test {}; # define TARGET "test.h" # define LIMIT SUB(SIZE, 1) # include "repeater.h" #else template <class R COMMA_IF_NONZERO(CURRENT) REPEAT(CURRENT, REPEAT_PARAM)> struct test<R COMMA_IF_NONZERO(CURRENT) REPEAT(CURRENT, REPEAT_VAR) COMMA_IF_NONZERO(SUB(SIZE, CURRENT)) REPEAT(SUB(SIZE, CURRENT), REPEAT_NONE)> {}; #endif iterating state initial state repetition entry-point
  • 22. boost pp • boost preprocess library – BOOST_PP_CAT – BOOST_PP_ENUM_PARAMS – BOOST_PP_REPEAT – BOOST_PP_COMMA_IF – BOOST_PP_SUB – BOOST_PP_DEC – BOOST_PP_WHILE – BOOST_PP_ITERATE 22
  • 23. boost pp (cont.) • many predefined macros functions – Arithmetic, Logical, and Comparison Operations – Control Structures – Token Pasting(argument selection) – Data Types(sequence, tuple, array, list) • well-optimized expand complexity 23 # define BOOST_PP_NODE_ENTRY_256(p) BOOST_PP_NODE_128(p)(p)(p)(p)(p)(p)(p)(p) # define BOOST_PP_NODE_ENTRY_128(p) BOOST_PP_NODE_64(p)(p)(p)(p)(p)(p)(p) // ... # define BOOST_PP_NODE_ENTRY_2(p) BOOST_PP_NODE_1(p)
  • 24. boost pp (cont.) • supports 256 reentrancy • supports 3 dimension (concurrently expandable count) 24 # define BOOST_PP_DEC_0 0 # define BOOST_PP_DEC_1 0 // ... # define BOOST_PP_DEC_255 254 # define BOOST_PP_DEC_256 255 # define BOOST_PP_REPEAT_1(c, m, d) BOOST_PP_REPEAT_1_I(c, m, d) # define BOOST_PP_REPEAT_2(c, m, d) BOOST_PP_REPEAT_2_I(c, m, d) # define BOOST_PP_REPEAT_3(c, m, d) BOOST_PP_REPEAT_3_I(c, m, d)
  • 25. Summary • Don't repeat yourself! • reduce boilerplate code using preprocess programming • but, your compile time is also boosted! 25