SlideShare a Scribd company logo
1 of 26
Download to read offline
C++ Ext
               e
               n
               s
               i
               o
@phil_nash     n Methods
class	
  A:

	
  foo()
	
  bar()

	
  data
class	
  A:

	
  foo()
              +	
  explode() ?
	
  bar()

	
  data
Dynamic
languages?
setattr(cls,	
  func.__name__,
	
  	
  	
  	
  	
  	
  	
  	
  types.MethodType(func,	
  cls))
setattr(cls,	
  func.__name__,
	
  	
  	
  	
  	
  	
  	
  	
  types.MethodType(func,	
  cls))

var	
  a	
  =	
  {};
a.f1	
  =	
  function(){};
setattr(cls,	
  func.__name__,
	
  	
  	
  	
  	
  	
  	
  	
  types.MethodType(func,	
  cls))

var	
  a	
  =	
  {};
a.f1	
  =	
  function(){};

struct	
  objc_method	
  myMethod;
myMethod.method_name	
  =	
  sel_registerName("sayHello");
myMethod.method_imp	
  	
  =	
  sayHello;
	
  
struct	
  objc_method_list	
  *	
  myMethodList;
myMethodList	
  =	
  malloc	
  (sizeof(struct	
  objc_method_list));
myMethodList-­‐>method_count	
  =	
  1;
myMethodList-­‐>method_list[0]	
  =	
  myMethod;
	
  	
  
class_addMethods	
  (	
  [EmptyClass	
  class],	
  myMethodList	
  );
Static
languages?
namespace	
  ExtensionMethods	
  {
	
  	
  	
  	
  public	
  static	
  class	
  MyExtensions	
  {
	
  	
  	
  	
  	
  	
  	
  	
  public	
  static	
  int	
  WordCount(this	
  String	
  str)	
  {
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  return	
  str.Split(new	
  char[]	
  {	
  '	
  ',	
  '.',	
  '?'	
  },	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  StringSplitOptions.RemoveEmptyEntries).Length;
	
  	
  	
  	
  	
  	
  	
  	
  }
	
  	
  	
  	
  }	
  	
  	
  
}
namespace	
  ExtensionMethods	
  {
 	
  	
  	
  	
  public	
  static	
  class	
  MyExtensions	
  {
 	
  	
  	
  	
  	
  	
  	
  	
  public	
  static	
  int	
  WordCount(this	
  String	
  str)	
  {
 	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  return	
  str.Split(new	
  char[]	
  {	
  '	
  ',	
  '.',	
  '?'	
  },	
  
 	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  StringSplitOptions.RemoveEmptyEntries).Length;
 	
  	
  	
  	
  	
  	
  	
  	
  }
 	
  	
  	
  	
  }	
  	
  	
  
 }



@implementation NSString (reverse)
 
-(NSString *) reverseString {
  NSMutableString *reversedStr;
  int len = [self length];
  reversedStr = [NSMutableString stringWithCapacity:len];
  while (len > 0)
    [reversedStr appendString:
         [NSString stringWithFormat:@"%C", [self characterAtIndex:--len]]];                                                                                            
  return reversedStr;
}
C++ ?
The
C++   Interface
       principle
namespace	
  NS	
  {
	
  	
  	
  	
  class	
  T	
  {	
  };
	
  	
  	
  	
  void	
  f(	
  T	
  );
}	
  

int	
  main()	
  {
	
  	
  	
  	
  NS::T	
  object;
	
  	
  	
  	
  f(object);
}
namespace	
  NS	
  {
	
  	
  	
  	
  class	
  T	
  {	
  };
	
  	
  	
  	
  void	
  f(	
  T	
  );
}	
  

int	
  main()	
  {
	
  	
  	
  	
  NS::T	
  object;
	
  	
  	
  	
  object.f();
}
namespace	
  NS	
  {
	
  	
  	
  	
  class	
  T	
  {	
  };
	
  	
  	
  	
  void	
  f(	
  T	
  );
}	
  

int	
  main()	
  {
	
  	
  	
  	
  NS::T*	
  object	
  =	
  new	
  NS::T();
	
  	
  	
  	
  object-­‐>f();
}
object-­‐>f()
object<-­‐f()
struct Widget : Extendible<Widget> {
    Widget( int size, int weight ) : size( size ), weight( weight ) {}

     int size;
     int weight;
};
struct Widget : Extendible<Widget> {
    Widget( int size, int weight ) : size( size ), weight( weight ) {}

     int size;
     int weight;
};

struct print : ExtMethod<print> {
    void operator()( Widget& w ) {
        std::cout << "size: " << w.size << ", weight: " << w.weight << std::endl;
    }
};




                                                  Widget w( 4, 10 );
                                                  w<-print();
struct Widget : Extendible<Widget> {
    Widget( int size, int weight ) : size( size ), weight( weight ) {}

     int size;
     int weight;
};

struct print : ExtMethod<print> {
    void operator()( Widget& w ) {
        std::cout << "size: " << w.size << ", weight: " << w.weight << std::endl;
    }
};


struct density : ExtMethod<density, float> {
    float operator()( Widget& w ) {
       return (float)(w.weight / w.size);
    }
};
                                                  Widget w( 4, 10 );
                                                  w<-print();
                                                  float d = w<-density();
template<typename T, typename ReturnT=void>
struct ExtMethod {
    ExtMethod& operator - () {
        return *this;
    }
    template<typename U>
    ReturnT operator()( U& obj ) {
        return static_cast<T*>(this)->operator()( obj );
    }
};




template<typename Derived>
struct Extendible
{
    template<typename T, typename ReturnT>
    ReturnT operator < ( ExtMethod<T, ReturnT>& extMethod ) {
        return extMethod( static_cast<Derived&>( *this ) );
    }
};
template<typename T, typename ReturnT=void>
struct ExtMethod {
    ExtMethod& operator - () {
        return *this;
    }
    template<typename U>
    ReturnT operator()( U& obj ) {
        return static_cast<T*>(this)->operator()( obj );
    }
};




template<typename Derived>
struct Extendible
{
    template<typename T, typename ReturnT>
    ReturnT operator < ( ExtMethod<T, ReturnT>& extMethod ) {
        return extMethod( static_cast<Derived&>( *this ) );
    }
};
template<typename T, typename ReturnT=void>
    struct ExtMethod {

                                                               e!
        ExtMethod& operator - () {

        }
            return *this;

                                                           c od
        template<typename U>
                                                   ion
                                                ct
        ReturnT operator()( U& obj ) {

                                        u
            return static_cast<T*>(this)->operator()( obj );
                                       d
                                     ro
        }
    };

                                 in p
                     this
                  do
    template<typename Derived>

          n    ’t
    struct Extendible
    {
         o
     se d
        template<typename T, typename ReturnT>


   ea
        ReturnT operator < ( ExtMethod<T, ReturnT>& extMethod ) {


Pl  };
        }
            return extMethod( static_cast<Derived&>( *this ) );

More Related Content

What's hot

JAVA THREADS.pdf
JAVA THREADS.pdfJAVA THREADS.pdf
JAVA THREADS.pdfMohit Kumar
 
Autovacuum, explained for engineers, new improved version PGConf.eu 2015 Vienna
Autovacuum, explained for engineers, new improved version PGConf.eu 2015 ViennaAutovacuum, explained for engineers, new improved version PGConf.eu 2015 Vienna
Autovacuum, explained for engineers, new improved version PGConf.eu 2015 ViennaPostgreSQL-Consulting
 
Graylog is the New Black
Graylog is the New BlackGraylog is the New Black
Graylog is the New BlackMegan Roddie
 
[Pgday.Seoul 2021] 2. Porting Oracle UDF and Optimization
[Pgday.Seoul 2021] 2. Porting Oracle UDF and Optimization[Pgday.Seoul 2021] 2. Porting Oracle UDF and Optimization
[Pgday.Seoul 2021] 2. Porting Oracle UDF and OptimizationPgDay.Seoul
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkArun Mehra
 
Functional programming
Functional programmingFunctional programming
Functional programmingijcd
 
[0410 박민근] 기술 면접시 자주 나오는 문제들
[0410 박민근] 기술 면접시 자주 나오는 문제들[0410 박민근] 기술 면접시 자주 나오는 문제들
[0410 박민근] 기술 면접시 자주 나오는 문제들MinGeun Park
 
Input output files in java
Input output files in javaInput output files in java
Input output files in javaKavitha713564
 
[150124 박민근] 모바일 게임 개발에서 루아 스크립트 활용하기
[150124 박민근] 모바일 게임 개발에서 루아 스크립트 활용하기[150124 박민근] 모바일 게임 개발에서 루아 스크립트 활용하기
[150124 박민근] 모바일 게임 개발에서 루아 스크립트 활용하기MinGeun Park
 
15 algoritmos de busca em tabelas - sequencial e binaria
15   algoritmos de busca em tabelas - sequencial e binaria15   algoritmos de busca em tabelas - sequencial e binaria
15 algoritmos de busca em tabelas - sequencial e binariaRicardo Bolanho
 
Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Kanika Gera
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageAniruddha Chakrabarti
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And MultithreadingShraddha
 
Monad Laws Must be Checked
Monad Laws Must be CheckedMonad Laws Must be Checked
Monad Laws Must be CheckedPhilip Schwarz
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engineDuoyi Wu
 

What's hot (20)

JAVA THREADS.pdf
JAVA THREADS.pdfJAVA THREADS.pdf
JAVA THREADS.pdf
 
PostgreSQL
PostgreSQLPostgreSQL
PostgreSQL
 
Autovacuum, explained for engineers, new improved version PGConf.eu 2015 Vienna
Autovacuum, explained for engineers, new improved version PGConf.eu 2015 ViennaAutovacuum, explained for engineers, new improved version PGConf.eu 2015 Vienna
Autovacuum, explained for engineers, new improved version PGConf.eu 2015 Vienna
 
Clang tidy
Clang tidyClang tidy
Clang tidy
 
Graylog is the New Black
Graylog is the New BlackGraylog is the New Black
Graylog is the New Black
 
[Pgday.Seoul 2021] 2. Porting Oracle UDF and Optimization
[Pgday.Seoul 2021] 2. Porting Oracle UDF and Optimization[Pgday.Seoul 2021] 2. Porting Oracle UDF and Optimization
[Pgday.Seoul 2021] 2. Porting Oracle UDF and Optimization
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
[0410 박민근] 기술 면접시 자주 나오는 문제들
[0410 박민근] 기술 면접시 자주 나오는 문제들[0410 박민근] 기술 면접시 자주 나오는 문제들
[0410 박민근] 기술 면접시 자주 나오는 문제들
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
[150124 박민근] 모바일 게임 개발에서 루아 스크립트 활용하기
[150124 박민근] 모바일 게임 개발에서 루아 스크립트 활용하기[150124 박민근] 모바일 게임 개발에서 루아 스크립트 활용하기
[150124 박민근] 모바일 게임 개발에서 루아 스크립트 활용하기
 
15 algoritmos de busca em tabelas - sequencial e binaria
15   algoritmos de busca em tabelas - sequencial e binaria15   algoritmos de busca em tabelas - sequencial e binaria
15 algoritmos de busca em tabelas - sequencial e binaria
 
Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction
 
Java thread life cycle
Java thread life cycleJava thread life cycle
Java thread life cycle
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Monad Laws Must be Checked
Monad Laws Must be CheckedMonad Laws Must be Checked
Monad Laws Must be Checked
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engine
 

Viewers also liked

UX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesUX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesNed Potter
 
TDLS8000 Tunable Diode Laser Spectrometer
TDLS8000 Tunable Diode Laser SpectrometerTDLS8000 Tunable Diode Laser Spectrometer
TDLS8000 Tunable Diode Laser SpectrometerYokogawa
 
Extension approaches
Extension approachesExtension approaches
Extension approachesMarxism
 
Farm management
Farm management Farm management
Farm management Nadia
 
Stomatal function and cam photosynthesis
Stomatal function and cam photosynthesisStomatal function and cam photosynthesis
Stomatal function and cam photosynthesisMark McGinley
 
AGRI 4411 Farm Management Chapter 2
AGRI 4411 Farm Management Chapter 2AGRI 4411 Farm Management Chapter 2
AGRI 4411 Farm Management Chapter 2Rita Conley
 
Soil degradation and regeneration
Soil degradation and regenerationSoil degradation and regeneration
Soil degradation and regenerationBijesh Mishra
 
Poultry Farm Management System
Poultry Farm Management SystemPoultry Farm Management System
Poultry Farm Management Systembimoljit
 
Web Based Agriculture Information System
Web Based Agriculture Information SystemWeb Based Agriculture Information System
Web Based Agriculture Information SystemGihan Wikramanayake
 
Agricultural Extension and Communication
Agricultural Extension and CommunicationAgricultural Extension and Communication
Agricultural Extension and CommunicationKarl Obispo
 
Participatory Research and Extension Approaches (PREA)
Participatory Research and Extension Approaches (PREA)Participatory Research and Extension Approaches (PREA)
Participatory Research and Extension Approaches (PREA)africa-rising
 
Current approaches in extension
Current approaches in extensionCurrent approaches in extension
Current approaches in extensionYagnesh sondarva
 
Performance Management System
Performance Management SystemPerformance Management System
Performance Management SystemMayank Singh
 

Viewers also liked (20)

UX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesUX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and Archives
 
TDLS8000 Tunable Diode Laser Spectrometer
TDLS8000 Tunable Diode Laser SpectrometerTDLS8000 Tunable Diode Laser Spectrometer
TDLS8000 Tunable Diode Laser Spectrometer
 
Soil Degradation
Soil Degradation Soil Degradation
Soil Degradation
 
Participatory extension method
Participatory extension methodParticipatory extension method
Participatory extension method
 
Extension approaches
Extension approachesExtension approaches
Extension approaches
 
Farmer Management System
Farmer Management SystemFarmer Management System
Farmer Management System
 
Farm management
Farm management Farm management
Farm management
 
Stomatal function and cam photosynthesis
Stomatal function and cam photosynthesisStomatal function and cam photosynthesis
Stomatal function and cam photosynthesis
 
AGRI 4411 Farm Management Chapter 2
AGRI 4411 Farm Management Chapter 2AGRI 4411 Farm Management Chapter 2
AGRI 4411 Farm Management Chapter 2
 
2nd lecture on Farm Management
2nd lecture on Farm Management2nd lecture on Farm Management
2nd lecture on Farm Management
 
Pra methods
Pra methodsPra methods
Pra methods
 
Soil degradation and regeneration
Soil degradation and regenerationSoil degradation and regeneration
Soil degradation and regeneration
 
Poultry Farm Management System
Poultry Farm Management SystemPoultry Farm Management System
Poultry Farm Management System
 
Web Based Agriculture Information System
Web Based Agriculture Information SystemWeb Based Agriculture Information System
Web Based Agriculture Information System
 
Agricultural Extension and Communication
Agricultural Extension and CommunicationAgricultural Extension and Communication
Agricultural Extension and Communication
 
Participatory Research and Extension Approaches (PREA)
Participatory Research and Extension Approaches (PREA)Participatory Research and Extension Approaches (PREA)
Participatory Research and Extension Approaches (PREA)
 
Current approaches in extension
Current approaches in extensionCurrent approaches in extension
Current approaches in extension
 
Performance Management System
Performance Management SystemPerformance Management System
Performance Management System
 
Soil degradation
Soil degradationSoil degradation
Soil degradation
 
Final ppt
Final pptFinal ppt
Final ppt
 

Similar to C++ extension methods

An Introduction to Part of C++ STL
An Introduction to Part of C++ STLAn Introduction to Part of C++ STL
An Introduction to Part of C++ STL乐群 陈
 
include ltfunctionalgt include ltiteratorgt inclu.pdf
include ltfunctionalgt include ltiteratorgt inclu.pdfinclude ltfunctionalgt include ltiteratorgt inclu.pdf
include ltfunctionalgt include ltiteratorgt inclu.pdfnaslin841216
 
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.0Yaser Zhian
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Please code in C++ and do only the �TO DO�s and all of them. There a.pdf
Please code in C++ and do only the �TO DO�s and all of them. There a.pdfPlease code in C++ and do only the �TO DO�s and all of them. There a.pdf
Please code in C++ and do only the �TO DO�s and all of them. There a.pdffarankureshi
 
Monadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query ExpressionsMonadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query ExpressionsChris Eargle
 
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляSergey Platonov
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Codemotion
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...tdc-globalcode
 
Статичный SQL в С++14. Евгений Захаров ➠ CoreHard Autumn 2019
Статичный SQL в С++14. Евгений Захаров ➠  CoreHard Autumn 2019Статичный SQL в С++14. Евгений Захаров ➠  CoreHard Autumn 2019
Статичный SQL в С++14. Евгений Захаров ➠ CoreHard Autumn 2019corehard_by
 
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.docxDIPESH30
 
C++ Lambda and concurrency
C++ Lambda and concurrencyC++ Lambda and concurrency
C++ Lambda and concurrency명신 김
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfyamew16788
 
Aho-Corasick string matching algorithm
Aho-Corasick string matching algorithmAho-Corasick string matching algorithm
Aho-Corasick string matching algorithmTakatoshi Kondo
 

Similar to C++ extension methods (20)

An Introduction to Part of C++ STL
An Introduction to Part of C++ STLAn Introduction to Part of C++ STL
An Introduction to Part of C++ STL
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 
include ltfunctionalgt include ltiteratorgt inclu.pdf
include ltfunctionalgt include ltiteratorgt inclu.pdfinclude ltfunctionalgt include ltiteratorgt inclu.pdf
include ltfunctionalgt include ltiteratorgt inclu.pdf
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
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
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Please code in C++ and do only the �TO DO�s and all of them. There a.pdf
Please code in C++ and do only the �TO DO�s and all of them. There a.pdfPlease code in C++ and do only the �TO DO�s and all of them. There a.pdf
Please code in C++ and do only the �TO DO�s and all of them. There a.pdf
 
Monadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query ExpressionsMonadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query Expressions
 
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуля
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
C++11
C++11C++11
C++11
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
 
Статичный SQL в С++14. Евгений Захаров ➠ CoreHard Autumn 2019
Статичный SQL в С++14. Евгений Захаров ➠  CoreHard Autumn 2019Статичный SQL в С++14. Евгений Захаров ➠  CoreHard Autumn 2019
Статичный SQL в С++14. Евгений Захаров ➠ CoreHard Autumn 2019
 
Matuura cpp
Matuura cppMatuura cpp
Matuura cpp
 
The STL
The STLThe STL
The STL
 
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
 
C++ Lambda and concurrency
C++ Lambda and concurrencyC++ Lambda and concurrency
C++ Lambda and concurrency
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdf
 
Functional C++
Functional C++Functional C++
Functional C++
 
Aho-Corasick string matching algorithm
Aho-Corasick string matching algorithmAho-Corasick string matching algorithm
Aho-Corasick string matching algorithm
 

Recently uploaded

Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 

Recently uploaded (20)

Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

C++ extension methods

  • 1. C++ Ext e n s i o @phil_nash n Methods
  • 2. class  A:  foo()  bar()  data
  • 3. class  A:  foo() +  explode() ?  bar()  data
  • 5. setattr(cls,  func.__name__,                types.MethodType(func,  cls))
  • 6. setattr(cls,  func.__name__,                types.MethodType(func,  cls)) var  a  =  {}; a.f1  =  function(){};
  • 7. setattr(cls,  func.__name__,                types.MethodType(func,  cls)) var  a  =  {}; a.f1  =  function(){}; struct  objc_method  myMethod; myMethod.method_name  =  sel_registerName("sayHello"); myMethod.method_imp    =  sayHello;   struct  objc_method_list  *  myMethodList; myMethodList  =  malloc  (sizeof(struct  objc_method_list)); myMethodList-­‐>method_count  =  1; myMethodList-­‐>method_list[0]  =  myMethod;     class_addMethods  (  [EmptyClass  class],  myMethodList  );
  • 9. namespace  ExtensionMethods  {        public  static  class  MyExtensions  {                public  static  int  WordCount(this  String  str)  {                        return  str.Split(new  char[]  {  '  ',  '.',  '?'  },                                                            StringSplitOptions.RemoveEmptyEntries).Length;                }        }       }
  • 10. namespace  ExtensionMethods  {        public  static  class  MyExtensions  {                public  static  int  WordCount(this  String  str)  {                        return  str.Split(new  char[]  {  '  ',  '.',  '?'  },                                                            StringSplitOptions.RemoveEmptyEntries).Length;                }        }       } @implementation NSString (reverse)   -(NSString *) reverseString { NSMutableString *reversedStr; int len = [self length]; reversedStr = [NSMutableString stringWithCapacity:len]; while (len > 0) [reversedStr appendString: [NSString stringWithFormat:@"%C", [self characterAtIndex:--len]]];   return reversedStr; }
  • 11. C++ ?
  • 12. The C++ Interface principle
  • 13. namespace  NS  {        class  T  {  };        void  f(  T  ); }   int  main()  {        NS::T  object;        f(object); }
  • 14. namespace  NS  {        class  T  {  };        void  f(  T  ); }   int  main()  {        NS::T  object;        object.f(); }
  • 15. namespace  NS  {        class  T  {  };        void  f(  T  ); }   int  main()  {        NS::T*  object  =  new  NS::T();        object-­‐>f(); }
  • 18.
  • 19. struct Widget : Extendible<Widget> { Widget( int size, int weight ) : size( size ), weight( weight ) {} int size; int weight; };
  • 20. struct Widget : Extendible<Widget> { Widget( int size, int weight ) : size( size ), weight( weight ) {} int size; int weight; }; struct print : ExtMethod<print> { void operator()( Widget& w ) { std::cout << "size: " << w.size << ", weight: " << w.weight << std::endl; } }; Widget w( 4, 10 ); w<-print();
  • 21. struct Widget : Extendible<Widget> { Widget( int size, int weight ) : size( size ), weight( weight ) {} int size; int weight; }; struct print : ExtMethod<print> { void operator()( Widget& w ) { std::cout << "size: " << w.size << ", weight: " << w.weight << std::endl; } }; struct density : ExtMethod<density, float> { float operator()( Widget& w ) { return (float)(w.weight / w.size); } }; Widget w( 4, 10 ); w<-print(); float d = w<-density();
  • 22.
  • 23. template<typename T, typename ReturnT=void> struct ExtMethod { ExtMethod& operator - () { return *this; } template<typename U> ReturnT operator()( U& obj ) { return static_cast<T*>(this)->operator()( obj ); } }; template<typename Derived> struct Extendible { template<typename T, typename ReturnT> ReturnT operator < ( ExtMethod<T, ReturnT>& extMethod ) { return extMethod( static_cast<Derived&>( *this ) ); } };
  • 24.
  • 25. template<typename T, typename ReturnT=void> struct ExtMethod { ExtMethod& operator - () { return *this; } template<typename U> ReturnT operator()( U& obj ) { return static_cast<T*>(this)->operator()( obj ); } }; template<typename Derived> struct Extendible { template<typename T, typename ReturnT> ReturnT operator < ( ExtMethod<T, ReturnT>& extMethod ) { return extMethod( static_cast<Derived&>( *this ) ); } };
  • 26. template<typename T, typename ReturnT=void> struct ExtMethod { e! ExtMethod& operator - () { } return *this; c od template<typename U> ion ct ReturnT operator()( U& obj ) { u return static_cast<T*>(this)->operator()( obj ); d ro } }; in p this do template<typename Derived> n ’t struct Extendible { o se d template<typename T, typename ReturnT> ea ReturnT operator < ( ExtMethod<T, ReturnT>& extMethod ) { Pl }; } return extMethod( static_cast<Derived&>( *this ) );