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

OODP Unit 1 OOPs classes and objects
OODP Unit 1 OOPs classes and objectsOODP Unit 1 OOPs classes and objects
OODP Unit 1 OOPs classes and objectsShanmuganathan C
 
富士通によるFIDOソリューションの展開について
富士通によるFIDOソリューションの展開について富士通によるFIDOソリューションの展開について
富士通によるFIDOソリューションの展開についてFIDO Alliance
 
Zero-Knowledge Proofs in Light of Digital Identity
Zero-Knowledge Proofs in Light of Digital IdentityZero-Knowledge Proofs in Light of Digital Identity
Zero-Knowledge Proofs in Light of Digital IdentityClare Nelson, CISSP, CIPP-E
 
маркетинговая стратегия. презентация для клиента
маркетинговая стратегия. презентация для клиентамаркетинговая стратегия. презентация для клиента
маркетинговая стратегия. презентация для клиентаSe_Grey
 
【一般社員向け研修】ソリューション営業活動プロセスの理解と実践ノウハウ
【一般社員向け研修】ソリューション営業活動プロセスの理解と実践ノウハウ【一般社員向け研修】ソリューション営業活動プロセスの理解と実践ノウハウ
【一般社員向け研修】ソリューション営業活動プロセスの理解と実践ノウハウMasanori Saito
 
次世代 IDaaS のポイントは本人確認 NIST と、サプライチェーンセキュリティと、みなしご ID - OpenID Summit 2020
次世代 IDaaS のポイントは本人確認 NIST と、サプライチェーンセキュリティと、みなしご ID  - OpenID Summit 2020次世代 IDaaS のポイントは本人確認 NIST と、サプライチェーンセキュリティと、みなしご ID  - OpenID Summit 2020
次世代 IDaaS のポイントは本人確認 NIST と、サプライチェーンセキュリティと、みなしご ID - OpenID Summit 2020OpenID Foundation Japan
 
風險管理與危機管理 馬偕-Final-無動畫
風險管理與危機管理 馬偕-Final-無動畫風險管理與危機管理 馬偕-Final-無動畫
風險管理與危機管理 馬偕-Final-無動畫Alex Yin
 
Global Gender Gap Report 2023
Global Gender Gap Report 2023 Global Gender Gap Report 2023
Global Gender Gap Report 2023 Paperjam_redaction
 
見えてきた!? Windows Virtual Desktop のしくみ
見えてきた!? Windows Virtual Desktop のしくみ見えてきた!? Windows Virtual Desktop のしくみ
見えてきた!? Windows Virtual Desktop のしくみTakashi Ushigami
 
問題處理與策略規劃技巧 (淡江大學)
問題處理與策略規劃技巧 (淡江大學)問題處理與策略規劃技巧 (淡江大學)
問題處理與策略規劃技巧 (淡江大學)Yeong-Long Chen
 
0x002 - Windows Priv Esc - A Low Level Explanation of Token Theft
0x002 - Windows Priv Esc - A Low Level Explanation of Token Theft0x002 - Windows Priv Esc - A Low Level Explanation of Token Theft
0x002 - Windows Priv Esc - A Low Level Explanation of Token TheftRussell Sanford
 

What's hot (12)

OODP Unit 1 OOPs classes and objects
OODP Unit 1 OOPs classes and objectsOODP Unit 1 OOPs classes and objects
OODP Unit 1 OOPs classes and objects
 
富士通によるFIDOソリューションの展開について
富士通によるFIDOソリューションの展開について富士通によるFIDOソリューションの展開について
富士通によるFIDOソリューションの展開について
 
Zero-Knowledge Proofs in Light of Digital Identity
Zero-Knowledge Proofs in Light of Digital IdentityZero-Knowledge Proofs in Light of Digital Identity
Zero-Knowledge Proofs in Light of Digital Identity
 
маркетинговая стратегия. презентация для клиента
маркетинговая стратегия. презентация для клиентамаркетинговая стратегия. презентация для клиента
маркетинговая стратегия. презентация для клиента
 
【一般社員向け研修】ソリューション営業活動プロセスの理解と実践ノウハウ
【一般社員向け研修】ソリューション営業活動プロセスの理解と実践ノウハウ【一般社員向け研修】ソリューション営業活動プロセスの理解と実践ノウハウ
【一般社員向け研修】ソリューション営業活動プロセスの理解と実践ノウハウ
 
次世代 IDaaS のポイントは本人確認 NIST と、サプライチェーンセキュリティと、みなしご ID - OpenID Summit 2020
次世代 IDaaS のポイントは本人確認 NIST と、サプライチェーンセキュリティと、みなしご ID  - OpenID Summit 2020次世代 IDaaS のポイントは本人確認 NIST と、サプライチェーンセキュリティと、みなしご ID  - OpenID Summit 2020
次世代 IDaaS のポイントは本人確認 NIST と、サプライチェーンセキュリティと、みなしご ID - OpenID Summit 2020
 
風險管理與危機管理 馬偕-Final-無動畫
風險管理與危機管理 馬偕-Final-無動畫風險管理與危機管理 馬偕-Final-無動畫
風險管理與危機管理 馬偕-Final-無動畫
 
現場料品管理 material control
現場料品管理 material control現場料品管理 material control
現場料品管理 material control
 
Global Gender Gap Report 2023
Global Gender Gap Report 2023 Global Gender Gap Report 2023
Global Gender Gap Report 2023
 
見えてきた!? Windows Virtual Desktop のしくみ
見えてきた!? Windows Virtual Desktop のしくみ見えてきた!? Windows Virtual Desktop のしくみ
見えてきた!? Windows Virtual Desktop のしくみ
 
問題處理與策略規劃技巧 (淡江大學)
問題處理與策略規劃技巧 (淡江大學)問題處理與策略規劃技巧 (淡江大學)
問題處理與策略規劃技巧 (淡江大學)
 
0x002 - Windows Priv Esc - A Low Level Explanation of Token Theft
0x002 - Windows Priv Esc - A Low Level Explanation of Token Theft0x002 - Windows Priv Esc - A Low Level Explanation of Token Theft
0x002 - Windows Priv Esc - A Low Level Explanation of Token Theft
 

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

Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 

Recently uploaded (20)

Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 

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 ) );