Search code examples
c++c++11initializer-list

c++11 initializer list as an array


I have the following function

void f(double* arr) 
{ ... }

Is this a sensible way to call that function in C++11: f({10.0, 8.0});? Thanks.


Solution

  • One possible solution is to make a small wrapper around the f function:

    void f(double* arr){
    
    }
    void f_wrapper(std::vector<double> v){
        f(v.data());    
    }
    int main(){
      f_wrapper({1.,2.,3.});
    }
    

    or as @(Kerrek SB) mentioned:

    void f(const double* arr){
    
    }
    
    void f_wrapper(std::initializer_list<double> v){
        f(v.begin());
    }
    
    int main(){
       f_wrapper({1.,2.,3.});
    }