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

Rust Programming Language
Rust Programming LanguageRust Programming Language
Rust Programming LanguageJaeju Kim
 
Android Tamer: Virtual Machine for Android (Security) Professionals
Android Tamer: Virtual Machine for Android (Security) ProfessionalsAndroid Tamer: Virtual Machine for Android (Security) Professionals
Android Tamer: Virtual Machine for Android (Security) ProfessionalsAnant Shrivastava
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonAgung Wahyudi
 
Python Course for Beginners
Python Course for BeginnersPython Course for Beginners
Python Course for BeginnersNandakumar P
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programmingSrinivas Narasegouda
 
What's Wrong With Object-Oriented Programming?
What's Wrong With Object-Oriented Programming?What's Wrong With Object-Oriented Programming?
What's Wrong With Object-Oriented Programming?Yegor Bugayenko
 
Ruby Presentation
Ruby Presentation Ruby Presentation
Ruby Presentation platico_dev
 
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
Gor Nishanov,  C++ Coroutines – a negative overhead abstractionGor Nishanov,  C++ Coroutines – a negative overhead abstraction
Gor Nishanov, C++ Coroutines – a negative overhead abstractionSergey Platonov
 
Designing with malli
Designing with malliDesigning with malli
Designing with malliMetosin Oy
 
O que há de incrível sobre o Flutter
O que há de incrível sobre o FlutterO que há de incrível sobre o Flutter
O que há de incrível sobre o FlutterWiliam Buzatto
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming languageSlawomir Dorzak
 
Python | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialPython | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialQA TrainingHub
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummiesLuis Goldster
 
GO programming language
GO programming languageGO programming language
GO programming languagetung vu
 

What's hot (20)

Rust Programming Language
Rust Programming LanguageRust Programming Language
Rust Programming Language
 
Android Tamer: Virtual Machine for Android (Security) Professionals
Android Tamer: Virtual Machine for Android (Security) ProfessionalsAndroid Tamer: Virtual Machine for Android (Security) Professionals
Android Tamer: Virtual Machine for Android (Security) Professionals
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
An introduction to programming in Go
An introduction to programming in GoAn introduction to programming in Go
An introduction to programming in Go
 
GMock framework
GMock frameworkGMock framework
GMock framework
 
Go lang
Go langGo lang
Go lang
 
Python Course for Beginners
Python Course for BeginnersPython Course for Beginners
Python Course for Beginners
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Clean code
Clean codeClean code
Clean code
 
What's Wrong With Object-Oriented Programming?
What's Wrong With Object-Oriented Programming?What's Wrong With Object-Oriented Programming?
What's Wrong With Object-Oriented Programming?
 
Ruby Presentation
Ruby Presentation Ruby Presentation
Ruby Presentation
 
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
Gor Nishanov,  C++ Coroutines – a negative overhead abstractionGor Nishanov,  C++ Coroutines – a negative overhead abstraction
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
 
Designing with malli
Designing with malliDesigning with malli
Designing with malli
 
Golang
GolangGolang
Golang
 
Python
PythonPython
Python
 
O que há de incrível sobre o Flutter
O que há de incrível sobre o FlutterO que há de incrível sobre o Flutter
O que há de incrível sobre o Flutter
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming language
 
Python | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialPython | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python Tutorial
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
GO programming language
GO programming languageGO programming language
GO programming language
 

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
 
Aho-Corasick string matching algorithm
Aho-Corasick string matching algorithmAho-Corasick string matching algorithm
Aho-Corasick string matching algorithm
 
Lab 13
Lab 13Lab 13
Lab 13
 

Recently uploaded

AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101vincent683379
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxJennifer Lim
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityScyllaDB
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsStefano
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyJohn Staveley
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024Stephanie Beckett
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessUXDXConf
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FIDO Alliance
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoTAnalytics
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxAbida Shariff
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfFIDO Alliance
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaCzechDreamin
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...FIDO Alliance
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfFIDO Alliance
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераMark Opanasiuk
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlPeter Udo Diehl
 
Buy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptxBuy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptxEasyPrinterHelp
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationZilliz
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Julian Hyde
 
Designing for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastDesigning for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastUXDXConf
 

Recently uploaded (20)

AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
Buy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptxBuy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptx
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG Evaluation
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
Designing for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastDesigning for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at Comcast
 

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