Create Vector Of Functions
std::vector<function<void()>> functions;
template<class T,class Par>
void addFun(T t,Par v){
function<void()> lab=[t,v](){t(v);};
functions.push_back(lab);
}
void callAllFuns(){
for(auto& f:functions)
f();
}
main(){
auto labda=[](int i){qDebug()<<i;};
auto labda2=[](QString str){qDebug()<<str;};
addFun(labda,12);
addFun(labda2,QStringLiteral("hello world"));
callAllFuns();
}
template<class T,class ...Par>
void addFun(T t,Par ...v){
qDebug()<<"add function";
function<void()> lab=[t,v...](){t(v...);};
functions.push_back(lab);
}
addFun<void(*)(int,int)>([](int a,int b)->void{},12,13);
literal operator
QString operator "" _P(unsigned long long v){
qDebug()<<v;
return QString::number(v);
}
84394_P;
template like function
template<typename TT,typename... TTT>
class Myfun;
template<typename TT,typename... TTT>
class Myfun<TT(TTT...)>
{
public:
Myfun(std::function<TT(TTT...)> fun,TTT&&... ttt){
fun(std::forward<TTT>(ttt)...);
}
};
int main(int argc,const char *const *const argv) {
auto vfun=[](int v,int v2)->int{cout<<"we call function";return 0;};
Myfun<int(int,int)> fun(vfun,1,2);
return 0;
}
static global variables
Example:
//file 1
#include <stdio.h>
extern double x;
extern void func();
int main( int argc, char* argv[] )
{
func();
printf( "x = %lf\n", x );
/* Try to uses "static double x" */
}
//file 2
#include <stdio.h>
static double x;
void func()
{
x = 12345;
printf( "x = %lf\n", x );
/* uses "static double x" */
}
When you compile these programs, you will get an error:
Explanation:
- The static global variable x can only be access within File 2.
- The main() function is not stored in the same file !
Specify Template
template<typename I>
class A{
void fun();
};
template<>
class A<int>{
};
class B{
public:
template<class T>
void fun();
};
template <class T>
void B::fun(){
}
template <>
void B::fun<int>(){
}
template <class=int>
void B::fun(){
}
function return pointer of array
int (*fun())[3]{
int i[][3]={{1,2,3}};
return i;
}
int main(int argc,char *argv[])
{
int(*(*f)())[3]=fun;
}
pointer to integer
AA* a1=new AA();
uintptr_t po=(uintptr_t)a1;
qDebug()<<po<<sizeof(uintptr_t);
AA* a3=(AA*)po;
qDebug()<<a1<<"="<<a3;
delete a3;
in modern c++
the memory of returned object or value is saved to use an extern of function so there is no need to call copy or move constructor
A fun(){
A a(2);
cout<<&a<<endl;
return a;
}
int main(int argc,const char *argv[]){
A a=fun();
cout<<&a<<endl;//it have same address of object inside fun function
return 0;
}