This document discusses several C++ idioms:
RAII automates resource management by acquiring resources during object initialization and releasing them during destruction. Attorney-client separates interface from implementation by controlling friend access. Virtual friend functions simulate virtual friends. Base-from-member initializes bases from members using an additional base class. PIMPL hides implementation by placing class details in a pimpl pointer. Copy-on-write optimizes copying by delaying copies until an object is modified. SFINAE uses template argument properties to enable/disable functions. Tag dispatching selects functions at compile-time using empty tag structs and trait classes.
Не так давно Гор Нишанов представил свой доклад: C++ Coroutines a negative overhead abstraction. В этом докладе Гор упомянул, что предложенный дизайн корутин позволяет их использовать практически в любых окружениях, в том числе и с "бедным" C++ рантаймом.
Я решил попробовать запустить корутины в следующих окружениях: обычное приложение, драйвер ОС Windows, EFI приложение. Только в одном из этих окружений есть полноценный C++ рантайм и поддержка исключений, в остальных ничего этого нет. Более того, EFI приложение вообще выполняется до старта ОС.
Я хочу рассказать о том, как мне удалось запустить корутины в этих окружениях, поговорим о том, какие проблемы существуют в асинхронном системном программировании и как их можно обойти.
Не так давно Гор Нишанов представил свой доклад: C++ Coroutines a negative overhead abstraction. В этом докладе Гор упомянул, что предложенный дизайн корутин позволяет их использовать практически в любых окружениях, в том числе и с "бедным" C++ рантаймом.
Я решил попробовать запустить корутины в следующих окружениях: обычное приложение, драйвер ОС Windows, EFI приложение. Только в одном из этих окружений есть полноценный C++ рантайм и поддержка исключений, в остальных ничего этого нет. Более того, EFI приложение вообще выполняется до старта ОС.
Я хочу рассказать о том, как мне удалось запустить корутины в этих окружениях, поговорим о том, какие проблемы существуют в асинхронном системном программировании и как их можно обойти.
C++20 comes with some big new language features: modules, coroutines, concepts, spaceship, and many new libraries. But apart from all those, C++20 also offers many small language improvements, making C++ more powerful and expressive, but also safer and more consistent. This talk is an overview over all those smaller additions to the core language that will make your life easier. We will discuss much-needed improvements to existing facilities such as lambdas, CTAD, structured bindings, and initialisation, as well as brand-new language utilities that you may not yet have heard about!
Антон Бикинеев, Writing good std::future< C++ >Sergey Platonov
В докладе Антон расскажет о грядущих мажорных изменениях языка, которые, не войдя в Стандарт 17-го года и оставшись в Technical Specifications, будут ждать своего мержа в 20-м, а также быть уже реализованными в некоторых компиляторах. Осветятся также минорные, уже одобренные фичи следующего Стандарта, как языковые, так и библиотечные. Антон расскажет об их целях, покажет методы использования, а также осветит некоторые гайдлайны и трики.
Asynchronous operations are getting more and more popular. To the point that we are getting frameworks and environments revolving strictly around that concept. Boost.ASIO, Twisted and node.js are notable example. We will not explore that area. We will focus on techniques for making asynchronous more readable. We will present different currently used solutions. At the end we will introduce coroutines and explain the concept. We will show how these can be integrated with asynchronous code and what we benefit from using coroutines in asynchronous code.
Capture the Flag (CTF) are information security challenges. They are fun, but they also provide a opportunity to practise for real-world security challenges.
In this talk we present the concept of CTF. We focus on some tools used by our team, which can also be used to solve real-world problems.
Empty Base Class Optimisation, [[no_unique_address]] and other C++20 AttributesBartlomiej Filipek
Those are the slides from my presentation for our local C++ Cracow User Grup. This time I described what is empty base class optimisation, how it affects unique_ptr and also how can we simplify the code with C++20's new attribute: [[no_unique_address]].
2018 cosup-delete unused python code safely - englishJen Yee Hong
The talk is about doing cleanup and refactor for legacy Python code base in a safer way. I introduced several existing tools for this task and demonstrated how (surprisingly) Python ast module can also help in this case.
中文摘要:
不管是 open source 專案還是工作上,經過長時間開發累積,source code 內可能會殘留許多不再需要的 code,造成維護以及 refactor 的困難,也造成新手 trace code 時的障礙。
對 C/C++ 這類編譯式語言來說,開啟編譯器最佳化能自動清除 dead code,但對於 Python 這類動態語言,則沒有公認完美的方法。
本議程分享一些相關經驗,佐以利用 Python AST 的簡易自製工具,討論如何從較複雜的 python source tree 中,安全的清除不再需要的 code。
Code: https://github.com/PCMan/python-find-unused-func
C++20 comes with some big new language features: modules, coroutines, concepts, spaceship, and many new libraries. But apart from all those, C++20 also offers many small language improvements, making C++ more powerful and expressive, but also safer and more consistent. This talk is an overview over all those smaller additions to the core language that will make your life easier. We will discuss much-needed improvements to existing facilities such as lambdas, CTAD, structured bindings, and initialisation, as well as brand-new language utilities that you may not yet have heard about!
Антон Бикинеев, Writing good std::future< C++ >Sergey Platonov
В докладе Антон расскажет о грядущих мажорных изменениях языка, которые, не войдя в Стандарт 17-го года и оставшись в Technical Specifications, будут ждать своего мержа в 20-м, а также быть уже реализованными в некоторых компиляторах. Осветятся также минорные, уже одобренные фичи следующего Стандарта, как языковые, так и библиотечные. Антон расскажет об их целях, покажет методы использования, а также осветит некоторые гайдлайны и трики.
Asynchronous operations are getting more and more popular. To the point that we are getting frameworks and environments revolving strictly around that concept. Boost.ASIO, Twisted and node.js are notable example. We will not explore that area. We will focus on techniques for making asynchronous more readable. We will present different currently used solutions. At the end we will introduce coroutines and explain the concept. We will show how these can be integrated with asynchronous code and what we benefit from using coroutines in asynchronous code.
Capture the Flag (CTF) are information security challenges. They are fun, but they also provide a opportunity to practise for real-world security challenges.
In this talk we present the concept of CTF. We focus on some tools used by our team, which can also be used to solve real-world problems.
Empty Base Class Optimisation, [[no_unique_address]] and other C++20 AttributesBartlomiej Filipek
Those are the slides from my presentation for our local C++ Cracow User Grup. This time I described what is empty base class optimisation, how it affects unique_ptr and also how can we simplify the code with C++20's new attribute: [[no_unique_address]].
2018 cosup-delete unused python code safely - englishJen Yee Hong
The talk is about doing cleanup and refactor for legacy Python code base in a safer way. I introduced several existing tools for this task and demonstrated how (surprisingly) Python ast module can also help in this case.
中文摘要:
不管是 open source 專案還是工作上,經過長時間開發累積,source code 內可能會殘留許多不再需要的 code,造成維護以及 refactor 的困難,也造成新手 trace code 時的障礙。
對 C/C++ 這類編譯式語言來說,開啟編譯器最佳化能自動清除 dead code,但對於 Python 這類動態語言,則沒有公認完美的方法。
本議程分享一些相關經驗,佐以利用 Python AST 的簡易自製工具,討論如何從較複雜的 python source tree 中,安全的清除不再需要的 code。
Code: https://github.com/PCMan/python-find-unused-func
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...corehard_by
What do threads, atomic variables, mutexes, and conditional variables have in common? They are the basic building blocks of any concurrent application in C++, which are even for the experienced C++ programmers a big challenge. This massively changed with C++17 and change even more with C++20/23. What did we get with C++17, what can we hope for with C++20/23? With C++17, most of the standard template library algorithms are available in sequential, parallel, and vectorised variants. With the upcoming standards, we can look forward to executors, transactional memory, significantly improved futures and coroutines. To make it short. These are just the highlights from the concurrent and parallel perspective. Thus there is the hope that in the future C++ abstractions such as executors, transactional memory, futures and coroutines are used and that threads, atomic variables, mutexes and condition variables are just implementation details.
Advanced Flow Concepts Every Developer Should KnowPeter Caitens
Tim Combridge from Sensible Giraffe and Salesforce Ben presents some important tips that all developers should know when dealing with Flows in Salesforce.
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
Listen to the keynote address and hear about the latest developments from Rachana Ananthakrishnan and Ian Foster who review the updates to the Globus Platform and Service, and the relevance of Globus to the scientific community as an automation platform to accelerate scientific discovery.
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
Your Digital Assistant.
Making complex approach simple. Straightforward process saves time. No more waiting to connect with people that matter to you. Safety first is not a cliché - Securely protect information in cloud storage to prevent any third party from accessing data.
Would you rather make your visitors feel burdened by making them wait? Or choose VizMan for a stress-free experience? VizMan is an automated visitor management system that works for any industries not limited to factories, societies, government institutes, and warehouses. A new age contactless way of logging information of visitors, employees, packages, and vehicles. VizMan is a digital logbook so it deters unnecessary use of paper or space since there is no requirement of bundles of registers that is left to collect dust in a corner of a room. Visitor’s essential details, helps in scheduling meetings for visitors and employees, and assists in supervising the attendance of the employees. With VizMan, visitors don’t need to wait for hours in long queues. VizMan handles visitors with the value they deserve because we know time is important to you.
Feasible Features
One Subscription, Four Modules – Admin, Employee, Receptionist, and Gatekeeper ensures confidentiality and prevents data from being manipulated
User Friendly – can be easily used on Android, iOS, and Web Interface
Multiple Accessibility – Log in through any device from any place at any time
One app for all industries – a Visitor Management System that works for any organisation.
Stress-free Sign-up
Visitor is registered and checked-in by the Receptionist
Host gets a notification, where they opt to Approve the meeting
Host notifies the Receptionist of the end of the meeting
Visitor is checked-out by the Receptionist
Host enters notes and remarks of the meeting
Customizable Components
Scheduling Meetings – Host can invite visitors for meetings and also approve, reject and reschedule meetings
Single/Bulk invites – Invitations can be sent individually to a visitor or collectively to many visitors
VIP Visitors – Additional security of data for VIP visitors to avoid misuse of information
Courier Management – Keeps a check on deliveries like commodities being delivered in and out of establishments
Alerts & Notifications – Get notified on SMS, email, and application
Parking Management – Manage availability of parking space
Individual log-in – Every user has their own log-in id
Visitor/Meeting Analytics – Evaluate notes and remarks of the meeting stored in the system
Visitor Management System is a secure and user friendly database manager that records, filters, tracks the visitors to your organization.
"Secure Your Premises with VizMan (VMS) – Get It Now"
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
Large Language Models and the End of ProgrammingMatt Welsh
Talk by Matt Welsh at Craft Conference 2024 on the impact that Large Language Models will have on the future of software development. In this talk, I discuss the ways in which LLMs will impact the software industry, from replacing human software developers with AI, to replacing conventional software with models that perform reasoning, computation, and problem-solving.
Modern design is crucial in today's digital environment, and this is especially true for SharePoint intranets. The design of these digital hubs is critical to user engagement and productivity enhancement. They are the cornerstone of internal collaboration and interaction within enterprises.
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Check out the webinar slides to learn more about how XfilesPro transforms Salesforce document management by leveraging its world-class applications. For more details, please connect with sales@xfilespro.com
If you want to watch the on-demand webinar, please click here: https://www.xfilespro.com/webinars/salesforce-document-management-2-0-smarter-faster-better/
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
Designing for Privacy in Amazon Web ServicesKrzysztofKkol1
Data privacy is one of the most critical issues that businesses face. This presentation shares insights on the principles and best practices for ensuring the resilience and security of your workload.
Drawing on a real-life project from the HR industry, the various challenges will be demonstrated: data protection, self-healing, business continuity, security, and transparency of data processing. This systematized approach allowed to create a secure AWS cloud infrastructure that not only met strict compliance rules but also exceeded the client's expectations.
In software engineering, the right architecture is essential for robust, scalable platforms. Wix has undergone a pivotal shift from event sourcing to a CRUD-based model for its microservices. This talk will chart the course of this pivotal journey.
Event sourcing, which records state changes as immutable events, provided robust auditing and "time travel" debugging for Wix Stores' microservices. Despite its benefits, the complexity it introduced in state management slowed development. Wix responded by adopting a simpler, unified CRUD model. This talk will explore the challenges of event sourcing and the advantages of Wix's new "CRUD on steroids" approach, which streamlines API integration and domain event management while preserving data integrity and system resilience.
Participants will gain valuable insights into Wix's strategies for ensuring atomicity in database updates and event production, as well as caching, materialization, and performance optimization techniques within a distributed system.
Join us to discover how Wix has mastered the art of balancing simplicity and extensibility, and learn how the re-adoption of the modest CRUD has turbocharged their development velocity, resilience, and scalability in a high-growth environment.
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
Unlocking Business Potential: Tailored Technology Solutions by Prosigns
Discover how Prosigns, a leading technology solutions provider, partners with businesses to drive innovation and success. Our presentation showcases our comprehensive range of services, including custom software development, web and mobile app development, AI & ML solutions, blockchain integration, DevOps services, and Microsoft Dynamics 365 support.
Custom Software Development: Prosigns specializes in creating bespoke software solutions that cater to your unique business needs. Our team of experts works closely with you to understand your requirements and deliver tailor-made software that enhances efficiency and drives growth.
Web and Mobile App Development: From responsive websites to intuitive mobile applications, Prosigns develops cutting-edge solutions that engage users and deliver seamless experiences across devices.
AI & ML Solutions: Harnessing the power of Artificial Intelligence and Machine Learning, Prosigns provides smart solutions that automate processes, provide valuable insights, and drive informed decision-making.
Blockchain Integration: Prosigns offers comprehensive blockchain solutions, including development, integration, and consulting services, enabling businesses to leverage blockchain technology for enhanced security, transparency, and efficiency.
DevOps Services: Prosigns' DevOps services streamline development and operations processes, ensuring faster and more reliable software delivery through automation and continuous integration.
Microsoft Dynamics 365 Support: Prosigns provides comprehensive support and maintenance services for Microsoft Dynamics 365, ensuring your system is always up-to-date, secure, and running smoothly.
Learn how our collaborative approach and dedication to excellence help businesses achieve their goals and stay ahead in today's digital landscape. From concept to deployment, Prosigns is your trusted partner for transforming ideas into reality and unlocking the full potential of your business.
Join us on a journey of innovation and growth. Let's partner for success with Prosigns.
2. Topics Covered
▪ Introduction
▪ RAII
▪ Attorney client
▪ Virtual friend functions
▪ Base from member
▪ Address of
▪ PIMPL
▪ COW
▪ SFINAE and Type Traits
▪ Tag dispatching
4. RAII (Resource Acquisition Is Initialization)
▪ A fundamental programming idiom used
to automate resource management.
5. RAII
▪ Resources are acquired during initialization, when there is no
chance of them being used before they are available, and
released with the destruction of the same objects, which is
guaranteed to take place even in case of errors.
Typical uses :
▪ Obtaining memory from new, malloc, IMalloc::Alloc, etc. Which
must be matched with a call to delete, free, IMalloc::Free, etc.
▪ Opening a file, which must be closed.
▪ Synchronization primitives like monitors, critical sections, etc.
Which must be released to allow other threads to obtain them.
▪ Opening a network connection, database connection, Creating
a Windows GDI object, Opening a Registry handle, etc.
▪ Example : STL’s std::auto_ptr
6. Attorney-Client - The limitation
▪ Control the granularity of access to the implementation
details of a class.
▪ Friends in C++ is an all-or-nothing proposition.
A friend declaration in C++ gives complete access to the
internals of a class.
class Foo
{
private:
void A(int a);
void B(float b);
void C(double c);
friend class Bar;
};
class Bar
{
// This class needs access to Foo::A and Foo::B only.
// C++ friendship rules, however, give access to all the private members
of Foo.
};
7. Attorney-Client - The workaround
class Attorney;
class Client
{
private:
void A(int a);
void B(float b);
void C(double c);
friend class Attorney;
};
class Attorney
{
private:
Client c;
static void callA(int a) { c.A(a); }
static void callB(float b) { c.B(b); }
friend class Bar;
};
class Bar
{// Bar now has access to only Client::A and Client::B
through the Attorney.
};
8. Virtual friend functions
▪ Simulate a virtual friend function.
class Base
{
public:
friend ostream& operator << (ostream& o, const Base& b);
// ...
protected:
virtual void print(ostream& o) const
{ ... }
};
inline std::ostream& operator<< (std::ostream& o, const Base& b)
{
b.print(o); // delegate the work to a polymorphic member
function.
return o;
}
class Derived : public Base
{
protected:
virtual void print(ostream& o) const
{ ... }
};
9. Base from member
▪ To initialize a base class from a data-member of the
derived class.
▪ Data member cannot be initialized before initializing the
base class.
▪ Ron Klatchko and Dietmar Kühl developed a way around.
▪ Base classes are initialized in the order they are declared.
10. Base from member - The limitation
namespace std {
class streambuf;
class ostream {
explicit ostream(std::streambuf * buf);
//...
};
}
class fdoutbuf // A customization of streambuf
: public std::streambuf
{
public:
explicit fdoutbuf( int fd );
//...
};
class fdostream
: public std::ostream
{
protected:
fdoutbuf buf;
public:
explicit fdostream( int fd )
: buf( fd ), std::ostream( &buf )
// This is not allowed: buf can't be initialized before std::ostream.
// std::ostream needs a std::streambuf object defined inside fdoutbuf.
{}
};
11. Base from member - The workaround
class fdoutbuf_pbase // A newly introduced class
{
public:
fdoutbuf sbuffer; // The member moved 'up' the hierarchy.
explicit fdoutbuf_pbase(int fd) : sbuffer(fd)
{}
};
class fdostream : protected virtual fdoutbuf_pbase
, public std::ostream
{
public:
explicit fdostream(int fd) : fdoutbuf_pbase(fd), //
Initialize the newly added base before std::ostream.
std::ostream(&sbuffer) // Now safe to pass the pointer
{}
//...
};
12. Address of - The limitation
▪ Find address of an object of a class that has an
overloaded unary ampersand (&) operator.
▪ This function is already in the <memory> header of the
new C++ standard C++11.
14. PIMPL (Private Implementation)
▪ Described by Herb Sutter.
▪ To hide the implementation details of an interface from
ordinary clients.
▪ Technique to minimize coupling via the separation of
interface and implementation.
▪ Also known as Bridge pattern, Cheshire Cat, Handle/
Body.class Add
{
int x;
int y;
public:
Add() { }
int add();
};
15. #include “AddDetails.h"
#include " Add.h"
Add ::Add()
{
ptr = new AddDetails();
}
Add::~ Add()
{
delete ptr;
}
int Add::add()
{
return ptr -> add();
}
Add.cpp
class AddDetails;
class Add
{
AddDetails* ptr;
public:
Add();
~Add();
int add();
};
Add.h
#include " AddDetails.h";
int AddDetails::add()
{
return x+y;
}
AddDetails.cpp
class AddDetails
{
int x;
int y;
public:
AddDetails() { }
int add();
};
AddDetails.h
#include “Add.h"
int _tmain(int argc, _TCHAR* argv[])
{
Add obj;
int result = obj.add();
return 0;
}
Main.cpp
PIMPL
16. COW (Copy On Write)
▪ Copying an object can sometimes cause a performance
penalty.
▪ Achieve lazy copy optimization, do the work just when you
need because of efficiency.
▪ If objects are frequently copied but infrequently modified
later.
template <class T>
class CowPtr
{
public:
typedef boost::shared_ptr<T> RefPtr;
private:
RefPtr m_sp;
void detach()
{
T* tmp = m_sp.get();
if( !( tmp == 0 || m_sp.unique() ) ) {
m_sp = RefPtr( new T( *tmp ) );
}
}
public:
18. COW (Copy On Write)
char & String::operator[](int)
CowPtr<String> s1 = "Hello";
char &c = s1->operator[](4); // Non-const detachment does
nothing here
CowPtr<String> s2(s1); // Lazy-copy, shared state
c = '!'; // Uh-oh
19. SFINAE (Substitution Failure Is Not An Error)
▪ David Vandevoorde first introduced the acronym SFINAE.
▪ It allows a template to determine certain properties of its
template arguments at instantiation time.
▪ Many developers found the behavior useful for compile-
time introspection.
int negate(int& i) { return -i; }
template <class F>
typename F::result_type negate(const F& f) { return -f(); }
negate(1);
▪ Type Traits are classes to obtain type information on
compile-time.
20. SFINAE
#include <type_traits>
#include <iostream>
template<class T> // foo1 overloads are enabled via the return type
typename std::enable_if<std::is_floating_point<T>::value, T>::type
foo1(T t)
{
std::cout << "foo1: floatn"; return t;
}
//Using helper type
template<class T> std::enable_if_t<std::is_integral<T>::value, T> foo1(T t)
{
std::cout << "foo1: intn"; return t;
}
template<class T>// foo2 overload is enabled via a parameter
T foo2(T t, typename std::enable_if<std::is_integral<T>::value >::type* =0)
{
return t;
}
template<class T , // foo3 overload is enabled via a template parameter
class = typename std::enable_if<std::is_integral<T>::value>::type >
T foo3(T t) // note, function signature is unmodified
{
return t;
}
21. int main()
{
foo1(1.2); // OK, calls the first version of foo1()
foo1(10); // OK, calls the second version of foo1()
// foo2(0.1); // compile-time error
foo2(7); // OK
// foo3(1.2); // compile-time error
foo3(34); // OK
}
SFINAE
template<bool B, class T = void>
struct enable_if {};
template<class T>
struct enable_if<true, T>
{ typedef T type; };
22. Tag Dispatching
▪ Tag dispatching is a technique for compile time
dispatching between a few overloaded functions by using
the properties of a type.
void work_fast(int i) { /*fast implementation*/ }
void work_fast(long l) { /*fast implementation*/ }
void work_slow(float f) { /*slow implementation*/ }
void work_slow(double d) { /*slow implementation*/ }
int main ()
{
int w; long x;
float y; double z;
work_fast(w); work_fast(x);
work_slow(y); work_slow(z);
return 0;
}
23. Tag Dispatching
▪ Tag dispatching is a technique for compile time
dispatching between a few overloaded functions by using
the properties of a type.
struct fast_speed_tag {};
struct slow_speed_tag {};
template <typename T>
void work_dispatch (const T &val, const slow_speed_tag&)
{
std::cout << "slow" << std::endl;
}
template <typename T>
void work_dispatch (const T &val, const fast_speed_tag&)
{
std::cout << "fast" << std::endl;
}
24. template <typename T>
struct traits // default
{
typedef slow_speed_tag speed;
};
template <>
struct traits<int> { // we would do the same for long etc
typedef fast_speed_tag speed;
};
template <typename T>
void work (const T &val)
{
work_dispatch(val, typename traits<T>::speed());
}
int main ()
{
int x;
float y;
work(x); // fast
work(y); // slow
return 0;
}
Tag Dispatching
25. ▪ One of the best examples of the Tag dispatch technique is
the implementation of std::advance() within STL iterators.
▪ The tag types are empty structs that are never used. As
such, the compiler will usually be able to optimize and
make them totally disappear from the compiled code –
which makes this technique even more appealing.
Tag Dispatching