Variable number of parameters in function in C++

前端 未结 8 1863
借酒劲吻你
借酒劲吻你 2020-12-07 20:32

How I can have variable number of parameters in my function in C++.

Analog in C#:

public void Foo(params int[] a) {
    for (int i = 0; i < a.Leng         


        
8条回答
  •  不思量自难忘°
    2020-12-07 21:14

    Aside from the other answers, if you're just trying to pass an array of integers, why not:

    void func(const std::vector& p)
    {
        // ...
    }
    
    std::vector params;
    params.push_back(1);
    params.push_back(2);
    params.push_back(3);
    
    func(params);
    

    You can't call it in parameter, form, though. You'd have to use any of the variadic function listed in your answers. C++0x will allow variadic templates, which will make it type-safe, but for now it's basically memory and casting.

    You could emulate some sort of variadic parameter->vector thing:

    // would also want to allow specifying the allocator, for completeness
    template  
    std::vector gen_vec(void)
    {
        std::vector result(0);
        return result;
    }
    
    template  
    std::vector gen_vec(T a1)
    {
        std::vector result(1);
    
        result.push_back(a1);
    
        return result;
    }
    
    template  
    std::vector gen_vec(T a1, T a2)
    {
        std::vector result(1);
    
        result.push_back(a1);
        result.push_back(a2);
    
        return result;
    }
    
    template  
    std::vector gen_vec(T a1, T a2, T a3)
    {
        std::vector result(1);
    
        result.push_back(a1);
        result.push_back(a2);
        result.push_back(a3);
    
        return result;
    }
    
    // and so on, boost stops at nine by default for their variadic templates
    

    Usage:

    func(gen_vec(1,2,3));
    

提交回复
热议问题