C++ Notes

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 <class T,typename ...TT>
class A{

};
A<int(string,int,double)> a;

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