SlideShare a Scribd company logo
1 of 6
1C:my_docsvirtual_machinesvmware_playershared_foldergeneralcpp11_sample_linux.cpp
/*
* tuple_mapper.hpp
*
* Created on: 19 Feb 2014
* Author: Dr Russell John Childs.
*/
//=======================================================================================================
// COPYRIGHT NOTICE
// This code sample and ideas embodied remain the property of Dr Russell John Childs, PhD, and have been
// distributed as a representative example of my use of C++11 features.
//==========================================================================================================
============
#ifndef TUPLE_MAPPER_HPP_
#define TUPLE_MAPPER_HPP_
//=========================================================================
// Use Case:
// Several threads operate on a set of variables, one variable to each thread.
//
// A transaction thread pulls these variables into a transaction (e.g. relativistic transfer of four-
momentum).
// The transaction thread operates on temporary copies so the transaction can be rolled back.
//
// During the transaction, a thread may want to change a variable, but does not know the tuple
// index for an std::get<index>(transaction_tuple)=new_value
//
// Also, changing a variable inside the tuple will not be visible to the transaction thread so that it can
revert transaction.
//
// Solution:
// Threads use polymorphic function that forwards requests for a change to a variable
// to the transaction thread.
//
// Since the threads neither know the index for their variable in the tuple, nor could they store one since
// it is a runtime value, not a compile time value, they instead make their variable a unique user type:
// e.g. UniqueMapper<float, 10>(my_float, 20.6), the unique id here is 10.
//
// Unfortunately, std::get<MyType>(transaction_tuple)=new_val is not allowed (const return type), nor does
std::get<MyType>(transaction_tuple);
// even compile under g++ 4.8, even though it should, so
// have to implement our own version using multiple inheritance (see class TupleMapper)
//
// Compiling this code sample (Linux Mint - g++ 4.8)
// Uncomment main()
// File: my_file.cpp
// #include "[my_directory]/tuple_mapper.hpp"
//
// g++ -O0 -g3 -Wall -O2 -g -Wall -c -fmessage-length=0 -std=c++11
// -I/usr/lib/gcc/x86_64-linux-gnu/4.8/:/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../../x86_64-linux-gnu/
lib/x86_64-linux-gnu/4.8/:
// /usr/lib/gcc/x86_64-linux-gnu/4.8/../../../../x86_64-linux-gnu/lib/x86_64-linux-gnu/:/usr/lib/gcc/
x86_64-linux-gnu/4.8/../../../../x86_64-linux-gnu/lib/../lib/:
// /usr/lib/gcc/x86_64-linux-gnu/4.8/../../../x86_64-linux-gnu/4.8/:/usr/lib/gcc/x86_64-linux-gnu/4.8/.
./../../x86_64-linux-gnu/:
// /usr/lib/gcc/x86_64-linux-gnu/4.8/../../../../lib/:/lib/x86_64-linux-gnu/4.8/:/lib/x86_64-linux-gnu/
:/lib/../lib/:/usr/lib/x86_64-linux-gnu/4.8/:
// /usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../../x86_64-
linux-gnu/lib/:/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../:
// /lib/:/usr/lib/
// my_file.cpp
//=========================================================================
#include <typeinfo>
#include <cxxabi.h>
#include <iomanip>
#include <functional>
#include <iostream>
#include <atomic>
#include <string>
#include <vector>
#include <tuple>
2C:my_docsvirtual_machinesvmware_playershared_foldergeneralcpp11_sample_linux.cpp
//=======================================================================================
// Class: struct UniqueMapper (lightweight std::pair)
// Template parameters:
// Type: the underlying type, e.g. float, int, MyClass
// Unique: A unique unsigned*
// Usage:
// float float_1;
// float float_2;
// //unique float (copy by value)
// auto unique_1 = UniqueMapper<decltype(float_1),&S>(float_1);
// //unique float (copy by ref)
// auto unique_2 = UniqueMapper<decltype(float_2),&S>(std::ref(float_1).get());
//=======================================================================================
//Helper macro - usage:
// auto unique_1 = __GETUNIQUE__(float_1);
// auto unique_2 = __GETUNIQUE__(std::ref(float_1).get());
template<typename T> struct dummy{ dummy(){} };
#define __GETUNIQUE__(variable) [&]{static unsigned S; return UniqueMapper<decltype(variable),&S>(variable);
}()
template<typename Type, unsigned* Unique>
struct UniqueMapper
{
//----------------------------------------------------
// Ctor:
// Arguments:
// Type& variable: the initial value of the variable
//----------------------------------------------------
UniqueMapper( const Type& variable ) :
m_variable( variable )
{
}
//----------------------------------------------------
// Dtor
//----------------------------------------------------
~UniqueMapper( void )
{
}
//----------------------------------------------------
// Method: get
// Arguments:
// None.
// Return value:
// Underlying variable by ref.
//----------------------------------------------------
Type& get( void )
{
return m_variable;
}
private:
template<typename... T> friend class TupleMapper;
Type m_variable;
};
//=======================================================================================
// Class: struct TupleMapper
// Template parameters:
// Type: the underlying types, e.g. float, int, MyClass
// Usage: Only serves as primary template.
//=======================================================================================
template<typename... Type>
struct TupleMapper
{
};
//=======================================================================================
// Class: struct TupleMapper
// Template parameters:
3C:my_docsvirtual_machinesvmware_playershared_foldergeneralcpp11_sample_linux.cpp
// Type: the underlying types, e.g. float, int, MyClass
// UniqueID: the unique unsigned integers distinguishing underlying types, e.g. 1,2,3,4
// Usage:
// UniqueMapper<float, 1> float_1(10);
// UniqueMapper<float, 2> float_2(20);
// TupleMapper<UniqueMapper<float, 2>, UniqueMapper<float, 1>> tup(float_2, float_1);
// tup.get(float_1)=30; // type deduction
// tup.get<decltype(float_2)>()=float_2.get(); // explicit type declaration
//=======================================================================================
template<typename...Type, unsigned*... Unique>
struct TupleMapper<UniqueMapper<Type,Unique>...> : public UniqueMapper<Type, Unique>...
{
//----------------------------------------------------
// Ctor:
// Arguments:
// UniqueMapper<Type,UniqueID>&... maps: the unique variables
//----------------------------------------------------
TupleMapper( UniqueMapper<Type,Unique>... maps) :
UniqueMapper<Type, Unique>(maps)...
{
}
//----------------------------------------------------
// Dtor
//----------------------------------------------------
~TupleMapper( void )
{
}
//----------------------------------------------------
// Method: get
// Template parameters:
// T: the unique type, e.g. UniqueID<float, 3>
// Arguments:
// None
// Returns:
// Reference to underlying variable
// Usge: tuple_mapper.get(UniqueID<float, 1>) = 30;
//----------------------------------------------------
template<typename T > auto get( void )-> decltype(T::m_variable)&
{
return T::m_variable;
}
//----------------------------------------------------
// Method: get
// Template parameters:
// T: the underlying type, e.g. float, automatically obtained through type deduction
// U: the unique integer id, e.g. 3, automatically obtained through type deduction
// Arguments:
// Unique variable
// Returns:
// Reference to underlying variable
// Usage: tup_map.get<decltype(float_2)>() = 40;
//----------------------------------------------------
template<typename T, unsigned* U> auto get( const UniqueMapper<T,U>&) -> decltype(this->get
<UniqueMapper<T,U>>())
{
return get<UniqueMapper<T,U>>();
}
};
//=======================================
// Helper classes for extracting the type of a variable
//=======================================
//=======================================
// const char* demangle( const char *str )
// demangles C++ decorated names
//==========================================
const char* demangle( const char *str )
{
int status;
4C:my_docsvirtual_machinesvmware_playershared_foldergeneralcpp11_sample_linux.cpp
return abi::__cxa_demangle(str,0,0,&status);
}
//=======================================
// template<typename T> struct IsType
// When typeid is used on Type& it prints out "Type" rather than "Type&"
// This class forces typeid to print out "IsType<Type&>" enabling "Type&" to be extracted
//==========================================
template<typename T> struct IsType
{
};
//=======================================
// Following macros extract "Type&" substr from "IsType<Type&>" string
// Usage:
// For objects:
// float& my_float_ref = some_float_var;
// typeid(decltype(my_float_ref)).name(); - gives "float"
// GET_TYPE_NAME(my_float_ref); - gives "float&"
// For types:
// template< typename T> struct MyStruct
// {
// MyStruct( void ){ std::cout << GET_TEMPLATE_NAME(T) << std::emdl; } // MyStruct<int&> gives "int
&".
// } ;
//==========================================
#define GET_TYPE_NAME_STR(arg) std::string(demangle(typeid(IsType<decltype(arg)>).name()))
#define GET_TYPE_NAME(arg) GET_TYPE_NAME_STR(arg).substr(7, GET_TYPE_NAME_STR(arg).length()-8 )
#define GET_TYPE_NAME_STR_1(arg) std::string(demangle(typeid(IsType<arg>).name()))
#define GET_TEMPLATE_NAME(arg) GET_TYPE_NAME_STR_1(arg).substr(7, GET_TYPE_NAME_STR_1(arg).length()-8 )
template<typename First, typename... Rest> struct MetaProgramming
{
MetaProgramming( const int i = 0 )
{
float my_float;
float& my_float_ref = my_float;
//typeid doesn't display references
std::cout << "typeid: " << "= " << demangle(typeid(decltype(my_float_ref)).name()) << std::endl;
//display reference type of template parameters
std::cout << "Type " << i << "=" << GET_TEMPLATE_NAME(First) << std::endl;
MetaProgramming<Rest...> tmp(i+1);
}
};
template<typename First> struct MetaProgramming<First>
{
MetaProgramming( const int i = 0 )
{
//Display type of an object, IsType<First>()
std::cout << "Type " << i << "=" << GET_TYPE_NAME(IsType<First>()) << std::endl;
}
};
//=======================================
// Following runs the above classes for illustration purposes.
//=======================================
class TestTupleMapperAndMetaProgramming
{
public:
TestTupleMapperAndMetaProgramming(void)
{
try
{
thread();
//throw std::runtime_error("test");
}
catch(std::exception& ex)
{
std::cout << "Execption" << std::endl
<< "File: " __FILE__ << ", Line: " << __LINE__
5C:my_docsvirtual_machinesvmware_playershared_foldergeneralcpp11_sample_linux.cpp
<< ", what()=" << ex.what() << std::endl;
}
}
~TestTupleMapperAndMetaProgramming( void )
{
}
template<typename T>
void compiler_bug(void)
{
//Without const qualifier T& become universal reference if T is a reference, e.g. T=float& --> float
&& (a universal ref)
//But, with const qualifier float&& should be an r-value, not a universal.
float my_float;
const T& tmp(my_float);
T const& tmp1(my_float);
std::cout << "compiler bug " << GET_TYPE_NAME(tmp) << std::endl;
}
void thread( void )
{
compiler_bug<float&&>();
compiler_bug<float&>();
compiler_bug<float>();
//Test __GETUNIQUE__ macro
int ii;
auto type = __GETUNIQUE__(ii);
std::cout << GET_TYPE_NAME( type ) << std::endl;
std::cout << std::boolalpha << (typeid(__GETUNIQUE__(ii)) != typeid(__GETUNIQUE__(ii))) << std::endl
;
//thread_f uses a float, but must make it a unique type, pass by ref
float f=-1;
auto u_f=__GETUNIQUE__(std::ref(f).get());
std::cout << GET_TYPE_NAME( u_f ) << std::endl;
//thread_i uses an int, but must make it a unique type, PASS by REF
int i=-1;
auto u_i=__GETUNIQUE__(std::ref(i).get());
std::cout << GET_TYPE_NAME( u_i ) << std::endl;
//thread_s uses a string, but must make it a unique type, PASS by REF
std::string s="-1";
auto u_s=__GETUNIQUE__(std::ref(s).get());
std::cout << GET_TYPE_NAME( u_f ) << std::endl;
//thread_j uses an int, but must make it a unique type, PASS by VALUE
int j=-1;
auto u_j=__GETUNIQUE__(j);
std::cout << GET_TYPE_NAME( u_j ) << std::endl;
//thread_tuple copies all above variables into a temporary tuple so that it can perform a
transaction without a commit
//If any of the above treads changes a variable, the transaction must be undone.
//The above threads change their variables through a polymorphic function that forwards request to
transaction thread.
TupleMapper<decltype(u_f), decltype(u_i), decltype(u_s), decltype(u_j)> tup(u_f, u_i, u_s, u_j);
std::cout << "initial values:" << std::endl
<< " tup.get<decltype(u_f)>()=" << tup.get<decltype(u_f)>()
<< ", f=" << f << std::endl
<< " tup.get<decltype(u_i)>()=" << tup.get<decltype(u_i)>()
<<", i=" << i << std::endl
<< " tup.get<decltype(u_s)>()=" << tup.get<decltype(u_s)>()
<< ", s=" << s << std::endl
<< " tup.get<decltype(u_j)>()=" << tup.get<decltype(u_j)>()
<< ", j=" << j << std::endl;
//thread i requests thread_tuple to change its value to 10, but does not know index for get<index>
(tuple)
//send u_i instead
6C:my_docsvirtual_machinesvmware_playershared_foldergeneralcpp11_sample_linux.cpp
u_i.get()=10;
//tuple_thread can now index tuple by type deduction
tup.get(u_i)=u_i.get();
//thread s requests thread_tuple to set its value to "s=10", but does not know index for get<index>
(tuple)
//send u_s instead
u_s.get()="s=10";
//tuple_thread can also index tuple by decltype
tup.get<decltype(u_s)>()=u_s.get(); //thread s sends UniqueMapper<std::string,4>
//thread f requests thread_tuple to set its value to 10.10, but does not know index for get<index>
(tuple)
tup.get(u_f)=10.10;//thread f sends UniqueMapper<float,3>
//thread j requests thread_tuple to set its value to 20, but does not know index for get<index>
(tuple)
tup.get(u_j)=20; //thread j sends UniqueMapper<int,2>
std::cout << "final values:" << std::endl
<< " tup.get<decltype(u_f)>()=" << tup.get<decltype(u_f)>()
<< ", f=" << f << std::endl
<< " tup.get<decltype(u_i)>()=" << tup.get<decltype(u_i)>()
<<", i=" << i << std::endl
<< " tup.get<decltype(u_s)>()=" << tup.get<decltype(u_s)>()
<< ", s=" << s << std::endl
<< " tup.get<decltype(u_j)>()=" << tup.get<decltype(u_j)>()
<< ", j=" << j << std::endl;
//Test example of metaprogramming
MetaProgramming<float&, int, std::string, std::vector<int>& > tm;
}
};
// executing illustration:
int main( void )
{
TestTupleMapperAndMetaProgramming();
}
#endif /* TUPLE_MAPPER_HPP_ */

More Related Content

What's hot

Php course-in-navimumbai
Php course-in-navimumbaiPhp course-in-navimumbai
Php course-in-navimumbaivibrantuser
 
實戰 Hhvm extension php conf 2014
實戰 Hhvm extension   php conf 2014實戰 Hhvm extension   php conf 2014
實戰 Hhvm extension php conf 2014Ricky Su
 
Barcelona 2010 hidden_features
Barcelona 2010 hidden_featuresBarcelona 2010 hidden_features
Barcelona 2010 hidden_featuresAnis Berejeb
 
Rooted 2010 ppp
Rooted 2010 pppRooted 2010 ppp
Rooted 2010 pppnoc_313
 
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...Mail.ru Group
 
ekb.py - Python VS ...
ekb.py - Python VS ...ekb.py - Python VS ...
ekb.py - Python VS ...it-people
 
PHP Object Injection Vulnerability in WordPress: an Analysis
PHP Object Injection Vulnerability in WordPress: an AnalysisPHP Object Injection Vulnerability in WordPress: an Analysis
PHP Object Injection Vulnerability in WordPress: an AnalysisPositive Hack Days
 
PHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP LimogesPHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP Limoges✅ William Pinaud
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
OpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell ScriptingOpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell ScriptingOpen Gurukul
 
The Beauty And The Beast Php N W09
The Beauty And The Beast Php N W09The Beauty And The Beast Php N W09
The Beauty And The Beast Php N W09Bastian Feder
 
08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboardsDenis Ristic
 
Talkaboutlithium
TalkaboutlithiumTalkaboutlithium
Talkaboutlithiumnoppoman722
 
The Beauty and the Beast
The Beauty and the BeastThe Beauty and the Beast
The Beauty and the BeastBastian Feder
 

What's hot (20)

Php course-in-navimumbai
Php course-in-navimumbaiPhp course-in-navimumbai
Php course-in-navimumbai
 
Feeds drupal cafe
Feeds drupal cafeFeeds drupal cafe
Feeds drupal cafe
 
實戰 Hhvm extension php conf 2014
實戰 Hhvm extension   php conf 2014實戰 Hhvm extension   php conf 2014
實戰 Hhvm extension php conf 2014
 
Barcelona 2010 hidden_features
Barcelona 2010 hidden_featuresBarcelona 2010 hidden_features
Barcelona 2010 hidden_features
 
Unix shell scripting
Unix shell scriptingUnix shell scripting
Unix shell scripting
 
Rooted 2010 ppp
Rooted 2010 pppRooted 2010 ppp
Rooted 2010 ppp
 
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
 
ekb.py - Python VS ...
ekb.py - Python VS ...ekb.py - Python VS ...
ekb.py - Python VS ...
 
PHP Object Injection Vulnerability in WordPress: an Analysis
PHP Object Injection Vulnerability in WordPress: an AnalysisPHP Object Injection Vulnerability in WordPress: an Analysis
PHP Object Injection Vulnerability in WordPress: an Analysis
 
Ow2 webinar erocci
Ow2 webinar erocciOw2 webinar erocci
Ow2 webinar erocci
 
SQLite Techniques
SQLite TechniquesSQLite Techniques
SQLite Techniques
 
PHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP LimogesPHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP Limoges
 
PHP5.5 is Here
PHP5.5 is HerePHP5.5 is Here
PHP5.5 is Here
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
OpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell ScriptingOpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell Scripting
 
The Beauty And The Beast Php N W09
The Beauty And The Beast Php N W09The Beauty And The Beast Php N W09
The Beauty And The Beast Php N W09
 
08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards
 
Talkaboutlithium
TalkaboutlithiumTalkaboutlithium
Talkaboutlithium
 
The Beauty and the Beast
The Beauty and the BeastThe Beauty and the Beast
The Beauty and the Beast
 
PerlScripting
PerlScriptingPerlScripting
PerlScripting
 

Viewers also liked

Simple shared mutex UML
Simple shared mutex UMLSimple shared mutex UML
Simple shared mutex UMLRussell Childs
 
Full resume dr_russell_john_childs_2016
Full resume dr_russell_john_childs_2016Full resume dr_russell_john_childs_2016
Full resume dr_russell_john_childs_2016Russell Childs
 
Dynamic programming burglar_problem
Dynamic programming burglar_problemDynamic programming burglar_problem
Dynamic programming burglar_problemRussell Childs
 
Cpp11 multithreading and_simd_linux_code
Cpp11 multithreading and_simd_linux_codeCpp11 multithreading and_simd_linux_code
Cpp11 multithreading and_simd_linux_codeRussell Childs
 
1 mathematical challenge_problem
1 mathematical challenge_problem1 mathematical challenge_problem
1 mathematical challenge_problemRussell Childs
 
3 mathematical challenge_code
3 mathematical challenge_code3 mathematical challenge_code
3 mathematical challenge_codeRussell Childs
 
Algorithms devised for a google interview
Algorithms devised for a google interviewAlgorithms devised for a google interview
Algorithms devised for a google interviewRussell Childs
 
Shared_memory_hash_table
Shared_memory_hash_tableShared_memory_hash_table
Shared_memory_hash_tableRussell Childs
 

Viewers also liked (10)

Simple shared mutex UML
Simple shared mutex UMLSimple shared mutex UML
Simple shared mutex UML
 
Full resume dr_russell_john_childs_2016
Full resume dr_russell_john_childs_2016Full resume dr_russell_john_childs_2016
Full resume dr_russell_john_childs_2016
 
Interview C++11 code
Interview C++11 codeInterview C++11 code
Interview C++11 code
 
Dynamic programming burglar_problem
Dynamic programming burglar_problemDynamic programming burglar_problem
Dynamic programming burglar_problem
 
Cpp11 multithreading and_simd_linux_code
Cpp11 multithreading and_simd_linux_codeCpp11 multithreading and_simd_linux_code
Cpp11 multithreading and_simd_linux_code
 
1 mathematical challenge_problem
1 mathematical challenge_problem1 mathematical challenge_problem
1 mathematical challenge_problem
 
Interview uml design
Interview uml designInterview uml design
Interview uml design
 
3 mathematical challenge_code
3 mathematical challenge_code3 mathematical challenge_code
3 mathematical challenge_code
 
Algorithms devised for a google interview
Algorithms devised for a google interviewAlgorithms devised for a google interview
Algorithms devised for a google interview
 
Shared_memory_hash_table
Shared_memory_hash_tableShared_memory_hash_table
Shared_memory_hash_table
 

Similar to Cpp11 sample linux

Auto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK NodesAuto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK Nodesnihiliad
 
Node.js basics
Node.js basicsNode.js basics
Node.js basicsBen Lin
 
Virtualization and automation of library software/machines + Puppet
Virtualization and automation of library software/machines + PuppetVirtualization and automation of library software/machines + Puppet
Virtualization and automation of library software/machines + PuppetOmar Reygaert
 
TYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkTYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkChristian Trabold
 
OpenHPC: Community Building Blocks for HPC Systems
OpenHPC: Community Building Blocks for HPC SystemsOpenHPC: Community Building Blocks for HPC Systems
OpenHPC: Community Building Blocks for HPC Systemsinside-BigData.com
 
A journey through the years of UNIX and Linux service management
A journey through the years of UNIX and Linux service managementA journey through the years of UNIX and Linux service management
A journey through the years of UNIX and Linux service managementLubomir Rintel
 
Dsa lab manual version 2
Dsa lab manual version 2Dsa lab manual version 2
Dsa lab manual version 2Dwight Sabio
 
Ansible for Beginners
Ansible for BeginnersAnsible for Beginners
Ansible for BeginnersArie Bregman
 
Automating Drupal Development: Makefiles, features and beyond
Automating Drupal Development: Makefiles, features and beyondAutomating Drupal Development: Makefiles, features and beyond
Automating Drupal Development: Makefiles, features and beyondNuvole
 
OpenWRT guide and memo
OpenWRT guide and memoOpenWRT guide and memo
OpenWRT guide and memo家榮 吳
 
Implementing of classical synchronization problem by using semaphores
Implementing of classical synchronization problem by using semaphoresImplementing of classical synchronization problem by using semaphores
Implementing of classical synchronization problem by using semaphoresGowtham Reddy
 
Projeto1617_FaseFinalMakefileall simulador monitormoni.docx
Projeto1617_FaseFinalMakefileall simulador monitormoni.docxProjeto1617_FaseFinalMakefileall simulador monitormoni.docx
Projeto1617_FaseFinalMakefileall simulador monitormoni.docxbriancrawford30935
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupSyedHaroonShah4
 
Marko Gargenta_Remixing android
Marko Gargenta_Remixing androidMarko Gargenta_Remixing android
Marko Gargenta_Remixing androidDroidcon Berlin
 
Orchestrated Functional Testing with Puppet-spec and Mspectator
Orchestrated Functional Testing with Puppet-spec and MspectatorOrchestrated Functional Testing with Puppet-spec and Mspectator
Orchestrated Functional Testing with Puppet-spec and MspectatorRaphaël PINSON
 

Similar to Cpp11 sample linux (20)

Auto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK NodesAuto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK Nodes
 
Node.js basics
Node.js basicsNode.js basics
Node.js basics
 
Virtualization and automation of library software/machines + Puppet
Virtualization and automation of library software/machines + PuppetVirtualization and automation of library software/machines + Puppet
Virtualization and automation of library software/machines + Puppet
 
TYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkTYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase framework
 
OpenHPC: Community Building Blocks for HPC Systems
OpenHPC: Community Building Blocks for HPC SystemsOpenHPC: Community Building Blocks for HPC Systems
OpenHPC: Community Building Blocks for HPC Systems
 
A journey through the years of UNIX and Linux service management
A journey through the years of UNIX and Linux service managementA journey through the years of UNIX and Linux service management
A journey through the years of UNIX and Linux service management
 
Dsa lab manual version 2
Dsa lab manual version 2Dsa lab manual version 2
Dsa lab manual version 2
 
C++ Core Guidelines
C++ Core GuidelinesC++ Core Guidelines
C++ Core Guidelines
 
fdsaf
fdsaffdsaf
fdsaf
 
Ansible for Beginners
Ansible for BeginnersAnsible for Beginners
Ansible for Beginners
 
Puppi. Puppet strings to the shell
Puppi. Puppet strings to the shellPuppi. Puppet strings to the shell
Puppi. Puppet strings to the shell
 
Automating Drupal Development: Makefiles, features and beyond
Automating Drupal Development: Makefiles, features and beyondAutomating Drupal Development: Makefiles, features and beyond
Automating Drupal Development: Makefiles, features and beyond
 
Sankula
SankulaSankula
Sankula
 
OpenWRT guide and memo
OpenWRT guide and memoOpenWRT guide and memo
OpenWRT guide and memo
 
Implementing of classical synchronization problem by using semaphores
Implementing of classical synchronization problem by using semaphoresImplementing of classical synchronization problem by using semaphores
Implementing of classical synchronization problem by using semaphores
 
Projeto1617_FaseFinalMakefileall simulador monitormoni.docx
Projeto1617_FaseFinalMakefileall simulador monitormoni.docxProjeto1617_FaseFinalMakefileall simulador monitormoni.docx
Projeto1617_FaseFinalMakefileall simulador monitormoni.docx
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
 
Intro to-puppet
Intro to-puppetIntro to-puppet
Intro to-puppet
 
Marko Gargenta_Remixing android
Marko Gargenta_Remixing androidMarko Gargenta_Remixing android
Marko Gargenta_Remixing android
 
Orchestrated Functional Testing with Puppet-spec and Mspectator
Orchestrated Functional Testing with Puppet-spec and MspectatorOrchestrated Functional Testing with Puppet-spec and Mspectator
Orchestrated Functional Testing with Puppet-spec and Mspectator
 

More from Russell Childs

spinor_quantum_simulator_user_guide_.pdf
spinor_quantum_simulator_user_guide_.pdfspinor_quantum_simulator_user_guide_.pdf
spinor_quantum_simulator_user_guide_.pdfRussell Childs
 
Feature extraction using adiabatic theorem
Feature extraction using adiabatic theoremFeature extraction using adiabatic theorem
Feature extraction using adiabatic theoremRussell Childs
 
Feature extraction using adiabatic theorem
Feature extraction using adiabatic theoremFeature extraction using adiabatic theorem
Feature extraction using adiabatic theoremRussell Childs
 
Wavelets_and_multiresolution_in_two_pages
Wavelets_and_multiresolution_in_two_pagesWavelets_and_multiresolution_in_two_pages
Wavelets_and_multiresolution_in_two_pagesRussell Childs
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.Russell Childs
 
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...Dirac demo (quantum mechanics with C++). Please note: There is a problem with...
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...Russell Childs
 
Design pattern to avoid downcasting
Design pattern to avoid downcastingDesign pattern to avoid downcasting
Design pattern to avoid downcastingRussell Childs
 
Full_resume_Dr_Russell_John_Childs
Full_resume_Dr_Russell_John_ChildsFull_resume_Dr_Russell_John_Childs
Full_resume_Dr_Russell_John_ChildsRussell Childs
 
Multithreaded sockets c++11
Multithreaded sockets c++11Multithreaded sockets c++11
Multithreaded sockets c++11Russell Childs
 
IBM Kinexa Prove It! C programming test results.
IBM Kinexa Prove It! C programming test results.IBM Kinexa Prove It! C programming test results.
IBM Kinexa Prove It! C programming test results.Russell Childs
 
IBM Kinexa Prove It! C++ programming test results.
IBM Kinexa Prove It! C++ programming test results.IBM Kinexa Prove It! C++ programming test results.
IBM Kinexa Prove It! C++ programming test results.Russell Childs
 
2 mathematical challenge_analysis_design_and_results
2 mathematical challenge_analysis_design_and_results2 mathematical challenge_analysis_design_and_results
2 mathematical challenge_analysis_design_and_resultsRussell Childs
 

More from Russell Childs (20)

spinor_quantum_simulator_user_guide_.pdf
spinor_quantum_simulator_user_guide_.pdfspinor_quantum_simulator_user_guide_.pdf
spinor_quantum_simulator_user_guide_.pdf
 
String searching o_n
String searching o_nString searching o_n
String searching o_n
 
String searching o_n
String searching o_nString searching o_n
String searching o_n
 
String searching o_n
String searching o_nString searching o_n
String searching o_n
 
String searching
String searchingString searching
String searching
 
Permute
PermutePermute
Permute
 
Permute
PermutePermute
Permute
 
Feature extraction using adiabatic theorem
Feature extraction using adiabatic theoremFeature extraction using adiabatic theorem
Feature extraction using adiabatic theorem
 
Feature extraction using adiabatic theorem
Feature extraction using adiabatic theoremFeature extraction using adiabatic theorem
Feature extraction using adiabatic theorem
 
Wavelets_and_multiresolution_in_two_pages
Wavelets_and_multiresolution_in_two_pagesWavelets_and_multiresolution_in_two_pages
Wavelets_and_multiresolution_in_two_pages
 
Relativity 2
Relativity 2Relativity 2
Relativity 2
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
 
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...Dirac demo (quantum mechanics with C++). Please note: There is a problem with...
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...
 
Design pattern to avoid downcasting
Design pattern to avoid downcastingDesign pattern to avoid downcasting
Design pattern to avoid downcasting
 
Full_resume_Dr_Russell_John_Childs
Full_resume_Dr_Russell_John_ChildsFull_resume_Dr_Russell_John_Childs
Full_resume_Dr_Russell_John_Childs
 
K d tree_cpp
K d tree_cppK d tree_cpp
K d tree_cpp
 
Multithreaded sockets c++11
Multithreaded sockets c++11Multithreaded sockets c++11
Multithreaded sockets c++11
 
IBM Kinexa Prove It! C programming test results.
IBM Kinexa Prove It! C programming test results.IBM Kinexa Prove It! C programming test results.
IBM Kinexa Prove It! C programming test results.
 
IBM Kinexa Prove It! C++ programming test results.
IBM Kinexa Prove It! C++ programming test results.IBM Kinexa Prove It! C++ programming test results.
IBM Kinexa Prove It! C++ programming test results.
 
2 mathematical challenge_analysis_design_and_results
2 mathematical challenge_analysis_design_and_results2 mathematical challenge_analysis_design_and_results
2 mathematical challenge_analysis_design_and_results
 

Recently uploaded

costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 

Recently uploaded (20)

costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 

Cpp11 sample linux

  • 1. 1C:my_docsvirtual_machinesvmware_playershared_foldergeneralcpp11_sample_linux.cpp /* * tuple_mapper.hpp * * Created on: 19 Feb 2014 * Author: Dr Russell John Childs. */ //======================================================================================================= // COPYRIGHT NOTICE // This code sample and ideas embodied remain the property of Dr Russell John Childs, PhD, and have been // distributed as a representative example of my use of C++11 features. //========================================================================================================== ============ #ifndef TUPLE_MAPPER_HPP_ #define TUPLE_MAPPER_HPP_ //========================================================================= // Use Case: // Several threads operate on a set of variables, one variable to each thread. // // A transaction thread pulls these variables into a transaction (e.g. relativistic transfer of four- momentum). // The transaction thread operates on temporary copies so the transaction can be rolled back. // // During the transaction, a thread may want to change a variable, but does not know the tuple // index for an std::get<index>(transaction_tuple)=new_value // // Also, changing a variable inside the tuple will not be visible to the transaction thread so that it can revert transaction. // // Solution: // Threads use polymorphic function that forwards requests for a change to a variable // to the transaction thread. // // Since the threads neither know the index for their variable in the tuple, nor could they store one since // it is a runtime value, not a compile time value, they instead make their variable a unique user type: // e.g. UniqueMapper<float, 10>(my_float, 20.6), the unique id here is 10. // // Unfortunately, std::get<MyType>(transaction_tuple)=new_val is not allowed (const return type), nor does std::get<MyType>(transaction_tuple); // even compile under g++ 4.8, even though it should, so // have to implement our own version using multiple inheritance (see class TupleMapper) // // Compiling this code sample (Linux Mint - g++ 4.8) // Uncomment main() // File: my_file.cpp // #include "[my_directory]/tuple_mapper.hpp" // // g++ -O0 -g3 -Wall -O2 -g -Wall -c -fmessage-length=0 -std=c++11 // -I/usr/lib/gcc/x86_64-linux-gnu/4.8/:/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../../x86_64-linux-gnu/ lib/x86_64-linux-gnu/4.8/: // /usr/lib/gcc/x86_64-linux-gnu/4.8/../../../../x86_64-linux-gnu/lib/x86_64-linux-gnu/:/usr/lib/gcc/ x86_64-linux-gnu/4.8/../../../../x86_64-linux-gnu/lib/../lib/: // /usr/lib/gcc/x86_64-linux-gnu/4.8/../../../x86_64-linux-gnu/4.8/:/usr/lib/gcc/x86_64-linux-gnu/4.8/. ./../../x86_64-linux-gnu/: // /usr/lib/gcc/x86_64-linux-gnu/4.8/../../../../lib/:/lib/x86_64-linux-gnu/4.8/:/lib/x86_64-linux-gnu/ :/lib/../lib/:/usr/lib/x86_64-linux-gnu/4.8/: // /usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../../x86_64- linux-gnu/lib/:/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../: // /lib/:/usr/lib/ // my_file.cpp //========================================================================= #include <typeinfo> #include <cxxabi.h> #include <iomanip> #include <functional> #include <iostream> #include <atomic> #include <string> #include <vector> #include <tuple>
  • 2. 2C:my_docsvirtual_machinesvmware_playershared_foldergeneralcpp11_sample_linux.cpp //======================================================================================= // Class: struct UniqueMapper (lightweight std::pair) // Template parameters: // Type: the underlying type, e.g. float, int, MyClass // Unique: A unique unsigned* // Usage: // float float_1; // float float_2; // //unique float (copy by value) // auto unique_1 = UniqueMapper<decltype(float_1),&S>(float_1); // //unique float (copy by ref) // auto unique_2 = UniqueMapper<decltype(float_2),&S>(std::ref(float_1).get()); //======================================================================================= //Helper macro - usage: // auto unique_1 = __GETUNIQUE__(float_1); // auto unique_2 = __GETUNIQUE__(std::ref(float_1).get()); template<typename T> struct dummy{ dummy(){} }; #define __GETUNIQUE__(variable) [&]{static unsigned S; return UniqueMapper<decltype(variable),&S>(variable); }() template<typename Type, unsigned* Unique> struct UniqueMapper { //---------------------------------------------------- // Ctor: // Arguments: // Type& variable: the initial value of the variable //---------------------------------------------------- UniqueMapper( const Type& variable ) : m_variable( variable ) { } //---------------------------------------------------- // Dtor //---------------------------------------------------- ~UniqueMapper( void ) { } //---------------------------------------------------- // Method: get // Arguments: // None. // Return value: // Underlying variable by ref. //---------------------------------------------------- Type& get( void ) { return m_variable; } private: template<typename... T> friend class TupleMapper; Type m_variable; }; //======================================================================================= // Class: struct TupleMapper // Template parameters: // Type: the underlying types, e.g. float, int, MyClass // Usage: Only serves as primary template. //======================================================================================= template<typename... Type> struct TupleMapper { }; //======================================================================================= // Class: struct TupleMapper // Template parameters:
  • 3. 3C:my_docsvirtual_machinesvmware_playershared_foldergeneralcpp11_sample_linux.cpp // Type: the underlying types, e.g. float, int, MyClass // UniqueID: the unique unsigned integers distinguishing underlying types, e.g. 1,2,3,4 // Usage: // UniqueMapper<float, 1> float_1(10); // UniqueMapper<float, 2> float_2(20); // TupleMapper<UniqueMapper<float, 2>, UniqueMapper<float, 1>> tup(float_2, float_1); // tup.get(float_1)=30; // type deduction // tup.get<decltype(float_2)>()=float_2.get(); // explicit type declaration //======================================================================================= template<typename...Type, unsigned*... Unique> struct TupleMapper<UniqueMapper<Type,Unique>...> : public UniqueMapper<Type, Unique>... { //---------------------------------------------------- // Ctor: // Arguments: // UniqueMapper<Type,UniqueID>&... maps: the unique variables //---------------------------------------------------- TupleMapper( UniqueMapper<Type,Unique>... maps) : UniqueMapper<Type, Unique>(maps)... { } //---------------------------------------------------- // Dtor //---------------------------------------------------- ~TupleMapper( void ) { } //---------------------------------------------------- // Method: get // Template parameters: // T: the unique type, e.g. UniqueID<float, 3> // Arguments: // None // Returns: // Reference to underlying variable // Usge: tuple_mapper.get(UniqueID<float, 1>) = 30; //---------------------------------------------------- template<typename T > auto get( void )-> decltype(T::m_variable)& { return T::m_variable; } //---------------------------------------------------- // Method: get // Template parameters: // T: the underlying type, e.g. float, automatically obtained through type deduction // U: the unique integer id, e.g. 3, automatically obtained through type deduction // Arguments: // Unique variable // Returns: // Reference to underlying variable // Usage: tup_map.get<decltype(float_2)>() = 40; //---------------------------------------------------- template<typename T, unsigned* U> auto get( const UniqueMapper<T,U>&) -> decltype(this->get <UniqueMapper<T,U>>()) { return get<UniqueMapper<T,U>>(); } }; //======================================= // Helper classes for extracting the type of a variable //======================================= //======================================= // const char* demangle( const char *str ) // demangles C++ decorated names //========================================== const char* demangle( const char *str ) { int status;
  • 4. 4C:my_docsvirtual_machinesvmware_playershared_foldergeneralcpp11_sample_linux.cpp return abi::__cxa_demangle(str,0,0,&status); } //======================================= // template<typename T> struct IsType // When typeid is used on Type& it prints out "Type" rather than "Type&" // This class forces typeid to print out "IsType<Type&>" enabling "Type&" to be extracted //========================================== template<typename T> struct IsType { }; //======================================= // Following macros extract "Type&" substr from "IsType<Type&>" string // Usage: // For objects: // float& my_float_ref = some_float_var; // typeid(decltype(my_float_ref)).name(); - gives "float" // GET_TYPE_NAME(my_float_ref); - gives "float&" // For types: // template< typename T> struct MyStruct // { // MyStruct( void ){ std::cout << GET_TEMPLATE_NAME(T) << std::emdl; } // MyStruct<int&> gives "int &". // } ; //========================================== #define GET_TYPE_NAME_STR(arg) std::string(demangle(typeid(IsType<decltype(arg)>).name())) #define GET_TYPE_NAME(arg) GET_TYPE_NAME_STR(arg).substr(7, GET_TYPE_NAME_STR(arg).length()-8 ) #define GET_TYPE_NAME_STR_1(arg) std::string(demangle(typeid(IsType<arg>).name())) #define GET_TEMPLATE_NAME(arg) GET_TYPE_NAME_STR_1(arg).substr(7, GET_TYPE_NAME_STR_1(arg).length()-8 ) template<typename First, typename... Rest> struct MetaProgramming { MetaProgramming( const int i = 0 ) { float my_float; float& my_float_ref = my_float; //typeid doesn't display references std::cout << "typeid: " << "= " << demangle(typeid(decltype(my_float_ref)).name()) << std::endl; //display reference type of template parameters std::cout << "Type " << i << "=" << GET_TEMPLATE_NAME(First) << std::endl; MetaProgramming<Rest...> tmp(i+1); } }; template<typename First> struct MetaProgramming<First> { MetaProgramming( const int i = 0 ) { //Display type of an object, IsType<First>() std::cout << "Type " << i << "=" << GET_TYPE_NAME(IsType<First>()) << std::endl; } }; //======================================= // Following runs the above classes for illustration purposes. //======================================= class TestTupleMapperAndMetaProgramming { public: TestTupleMapperAndMetaProgramming(void) { try { thread(); //throw std::runtime_error("test"); } catch(std::exception& ex) { std::cout << "Execption" << std::endl << "File: " __FILE__ << ", Line: " << __LINE__
  • 5. 5C:my_docsvirtual_machinesvmware_playershared_foldergeneralcpp11_sample_linux.cpp << ", what()=" << ex.what() << std::endl; } } ~TestTupleMapperAndMetaProgramming( void ) { } template<typename T> void compiler_bug(void) { //Without const qualifier T& become universal reference if T is a reference, e.g. T=float& --> float && (a universal ref) //But, with const qualifier float&& should be an r-value, not a universal. float my_float; const T& tmp(my_float); T const& tmp1(my_float); std::cout << "compiler bug " << GET_TYPE_NAME(tmp) << std::endl; } void thread( void ) { compiler_bug<float&&>(); compiler_bug<float&>(); compiler_bug<float>(); //Test __GETUNIQUE__ macro int ii; auto type = __GETUNIQUE__(ii); std::cout << GET_TYPE_NAME( type ) << std::endl; std::cout << std::boolalpha << (typeid(__GETUNIQUE__(ii)) != typeid(__GETUNIQUE__(ii))) << std::endl ; //thread_f uses a float, but must make it a unique type, pass by ref float f=-1; auto u_f=__GETUNIQUE__(std::ref(f).get()); std::cout << GET_TYPE_NAME( u_f ) << std::endl; //thread_i uses an int, but must make it a unique type, PASS by REF int i=-1; auto u_i=__GETUNIQUE__(std::ref(i).get()); std::cout << GET_TYPE_NAME( u_i ) << std::endl; //thread_s uses a string, but must make it a unique type, PASS by REF std::string s="-1"; auto u_s=__GETUNIQUE__(std::ref(s).get()); std::cout << GET_TYPE_NAME( u_f ) << std::endl; //thread_j uses an int, but must make it a unique type, PASS by VALUE int j=-1; auto u_j=__GETUNIQUE__(j); std::cout << GET_TYPE_NAME( u_j ) << std::endl; //thread_tuple copies all above variables into a temporary tuple so that it can perform a transaction without a commit //If any of the above treads changes a variable, the transaction must be undone. //The above threads change their variables through a polymorphic function that forwards request to transaction thread. TupleMapper<decltype(u_f), decltype(u_i), decltype(u_s), decltype(u_j)> tup(u_f, u_i, u_s, u_j); std::cout << "initial values:" << std::endl << " tup.get<decltype(u_f)>()=" << tup.get<decltype(u_f)>() << ", f=" << f << std::endl << " tup.get<decltype(u_i)>()=" << tup.get<decltype(u_i)>() <<", i=" << i << std::endl << " tup.get<decltype(u_s)>()=" << tup.get<decltype(u_s)>() << ", s=" << s << std::endl << " tup.get<decltype(u_j)>()=" << tup.get<decltype(u_j)>() << ", j=" << j << std::endl; //thread i requests thread_tuple to change its value to 10, but does not know index for get<index> (tuple) //send u_i instead
  • 6. 6C:my_docsvirtual_machinesvmware_playershared_foldergeneralcpp11_sample_linux.cpp u_i.get()=10; //tuple_thread can now index tuple by type deduction tup.get(u_i)=u_i.get(); //thread s requests thread_tuple to set its value to "s=10", but does not know index for get<index> (tuple) //send u_s instead u_s.get()="s=10"; //tuple_thread can also index tuple by decltype tup.get<decltype(u_s)>()=u_s.get(); //thread s sends UniqueMapper<std::string,4> //thread f requests thread_tuple to set its value to 10.10, but does not know index for get<index> (tuple) tup.get(u_f)=10.10;//thread f sends UniqueMapper<float,3> //thread j requests thread_tuple to set its value to 20, but does not know index for get<index> (tuple) tup.get(u_j)=20; //thread j sends UniqueMapper<int,2> std::cout << "final values:" << std::endl << " tup.get<decltype(u_f)>()=" << tup.get<decltype(u_f)>() << ", f=" << f << std::endl << " tup.get<decltype(u_i)>()=" << tup.get<decltype(u_i)>() <<", i=" << i << std::endl << " tup.get<decltype(u_s)>()=" << tup.get<decltype(u_s)>() << ", s=" << s << std::endl << " tup.get<decltype(u_j)>()=" << tup.get<decltype(u_j)>() << ", j=" << j << std::endl; //Test example of metaprogramming MetaProgramming<float&, int, std::string, std::vector<int>& > tm; } }; // executing illustration: int main( void ) { TestTupleMapperAndMetaProgramming(); } #endif /* TUPLE_MAPPER_HPP_ */