SlideShare a Scribd company logo
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

Fisika Induksi
Fisika InduksiFisika Induksi
Fisika Induksi
prihase
 
Usaha dan Energi
Usaha dan Energi Usaha dan Energi
Usaha dan Energi
SMPN 3 TAMAN SIDOARJO
 
Magnetic Effects of Electric Current for Grade 10th Students
Magnetic Effects of Electric Current for Grade 10th StudentsMagnetic Effects of Electric Current for Grade 10th Students
Magnetic Effects of Electric Current for Grade 10th Students
Murari Parashar
 
Moments
MomentsMoments
6. induksi elektromagnetik kelas 9
6. induksi elektromagnetik   kelas 96. induksi elektromagnetik   kelas 9
6. induksi elektromagnetik kelas 9Dimas Yossi P P
 
ppt hukum archimedes.pptx
ppt hukum archimedes.pptxppt hukum archimedes.pptx
ppt hukum archimedes.pptx
SriIndayani4
 
Linear momentum
Linear momentum Linear momentum
Linear momentum
Hamzabg
 
Radiasi benda-hitam SMA
Radiasi benda-hitam SMARadiasi benda-hitam SMA
Radiasi benda-hitam SMA
Irhuel_Abal2
 
Electrostatics
ElectrostaticsElectrostatics
Electrostatics
ermanoj1466
 
P5 Electric Circuits
P5 Electric CircuitsP5 Electric Circuits
P5 Electric Circuits
pedro proenca
 
SwiftUI and Combine All the Things
SwiftUI and Combine All the ThingsSwiftUI and Combine All the Things
SwiftUI and Combine All the Things
Scott Gardner
 
Mechanical energy
Mechanical energyMechanical energy
Mechanical energy
Siyavula
 
Chemistry notes class 11 chapter 3 classification of elements and periodicity...
Chemistry notes class 11 chapter 3 classification of elements and periodicity...Chemistry notes class 11 chapter 3 classification of elements and periodicity...
Chemistry notes class 11 chapter 3 classification of elements and periodicity...
AMARJEET KUMAR
 
Propertry of matter
Propertry of matterPropertry of matter
Propertry of matter
Shitanshu Desai
 
Gaya gerak listrik
Gaya gerak listrikGaya gerak listrik
Gaya gerak listrik
Andhryn Celica
 
GLBB Diperlambat
GLBB DiperlambatGLBB Diperlambat
GLBB Diperlambat
lissura chatami
 
Electricity as level
Electricity as levelElectricity as level
Electricity as level
IB School
 
GCSE Chemistry [C3]
GCSE Chemistry [C3]GCSE Chemistry [C3]
GCSE Chemistry [C3]
Katie B
 
ppt Listrik statis
ppt Listrik statisppt Listrik statis
ppt Listrik statis
Stikes BTH Tasikmalaya
 

What's hot (20)

Fisika Induksi
Fisika InduksiFisika Induksi
Fisika Induksi
 
Usaha dan Energi
Usaha dan Energi Usaha dan Energi
Usaha dan Energi
 
Magnetic Effects of Electric Current for Grade 10th Students
Magnetic Effects of Electric Current for Grade 10th StudentsMagnetic Effects of Electric Current for Grade 10th Students
Magnetic Effects of Electric Current for Grade 10th Students
 
Moments
MomentsMoments
Moments
 
6. induksi elektromagnetik kelas 9
6. induksi elektromagnetik   kelas 96. induksi elektromagnetik   kelas 9
6. induksi elektromagnetik kelas 9
 
Entropi
EntropiEntropi
Entropi
 
ppt hukum archimedes.pptx
ppt hukum archimedes.pptxppt hukum archimedes.pptx
ppt hukum archimedes.pptx
 
Linear momentum
Linear momentum Linear momentum
Linear momentum
 
Radiasi benda-hitam SMA
Radiasi benda-hitam SMARadiasi benda-hitam SMA
Radiasi benda-hitam SMA
 
Electrostatics
ElectrostaticsElectrostatics
Electrostatics
 
P5 Electric Circuits
P5 Electric CircuitsP5 Electric Circuits
P5 Electric Circuits
 
SwiftUI and Combine All the Things
SwiftUI and Combine All the ThingsSwiftUI and Combine All the Things
SwiftUI and Combine All the Things
 
Mechanical energy
Mechanical energyMechanical energy
Mechanical energy
 
Chemistry notes class 11 chapter 3 classification of elements and periodicity...
Chemistry notes class 11 chapter 3 classification of elements and periodicity...Chemistry notes class 11 chapter 3 classification of elements and periodicity...
Chemistry notes class 11 chapter 3 classification of elements and periodicity...
 
Propertry of matter
Propertry of matterPropertry of matter
Propertry of matter
 
Gaya gerak listrik
Gaya gerak listrikGaya gerak listrik
Gaya gerak listrik
 
GLBB Diperlambat
GLBB DiperlambatGLBB Diperlambat
GLBB Diperlambat
 
Electricity as level
Electricity as levelElectricity as level
Electricity as level
 
GCSE Chemistry [C3]
GCSE Chemistry [C3]GCSE Chemistry [C3]
GCSE Chemistry [C3]
 
ppt Listrik statis
ppt Listrik statisppt Listrik statis
ppt Listrik statis
 

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 Archives
Ned Potter
 
TDLS8000 Tunable Diode Laser Spectrometer
TDLS8000 Tunable Diode Laser SpectrometerTDLS8000 Tunable Diode Laser Spectrometer
TDLS8000 Tunable Diode Laser Spectrometer
Yokogawa
 
Soil Degradation
Soil Degradation Soil Degradation
Soil Degradation
Michael Newbold
 
Participatory extension method
Participatory extension methodParticipatory extension method
Extension approaches
Extension approachesExtension approaches
Extension approaches
Marxism
 
Farmer Management System
Farmer Management SystemFarmer Management System
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 photosynthesis
Mark McGinley
 
AGRI 4411 Farm Management Chapter 2
AGRI 4411 Farm Management Chapter 2AGRI 4411 Farm Management Chapter 2
AGRI 4411 Farm Management Chapter 2
Rita Conley
 
2nd lecture on Farm Management
2nd lecture on Farm Management2nd lecture on Farm Management
2nd lecture on Farm Management
Ministry of Animal Resources & Fisheries
 
Pra methods
Pra methodsPra methods
Pra methods
kppaul2009
 
Soil degradation and regeneration
Soil degradation and regenerationSoil degradation and regeneration
Soil degradation and regeneration
Bijesh Mishra
 
Poultry Farm Management System
Poultry Farm Management SystemPoultry Farm Management System
Poultry Farm Management System
bimoljit
 
Web Based Agriculture Information System
Web Based Agriculture Information SystemWeb Based Agriculture Information System
Web Based Agriculture Information System
Gihan Wikramanayake
 
Agricultural Extension and Communication
Agricultural Extension and CommunicationAgricultural Extension and Communication
Agricultural Extension and Communication
Karl 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 extension
Yagnesh sondarva
 
Performance Management System
Performance Management SystemPerformance Management System
Performance Management System
Mayank Singh
 
Soil degradation
Soil degradationSoil degradation
Final ppt
Final pptFinal ppt
Final ppt
Jyoti Jha
 

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
乐群 陈
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
sidra tauseef
 
include ltfunctionalgt include ltiteratorgt inclu.pdf
include ltfunctionalgt include ltiteratorgt inclu.pdfinclude ltfunctionalgt include ltiteratorgt inclu.pdf
include ltfunctionalgt include ltiteratorgt inclu.pdf
naslin841216
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
GlobalLogic Ukraine
 
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
Yaser 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.pdf
farankureshi
 
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
Chris 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
 
C++11
C++11C++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...
tdc-globalcode
 
Статичный SQL в С++14. Евгений Захаров ➠ CoreHard Autumn 2019
Статичный SQL в С++14. Евгений Захаров ➠  CoreHard Autumn 2019Статичный SQL в С++14. Евгений Захаров ➠  CoreHard Autumn 2019
Статичный SQL в С++14. Евгений Захаров ➠ CoreHard Autumn 2019
corehard_by
 
Matuura cpp
Matuura cppMatuura cpp
Matuura cpp
matuura_core
 
The STL
The STLThe STL
The STL
adil raja
 
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
 
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
yamew16788
 
Functional C++
Functional C++Functional C++
Functional C++
Kevlin Henney
 
Aho-Corasick string matching algorithm
Aho-Corasick string matching algorithmAho-Corasick string matching algorithm
Aho-Corasick string matching algorithm
Takatoshi 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

Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
Pixlogix Infotech
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
TIPNGVN2
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Zilliz
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 

Recently uploaded (20)

Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 

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