【问题标题】:How do I return the number of arguments of a function?如何返回函数的参数个数?
【发布时间】:2020-05-09 09:51:44
【问题描述】:

例如,如果我有

int MyFunction(int,...);//no. of parameters is unknown

在 main() 中

MyFunction(1,2,3,4);

返回值应该是 4。我试过 stdarg.h 但要使用它你必须知道参数的数量,所以它对我来说不成立。谢谢!

【问题讨论】:

标签: c++ function templates parameters variadic-templates


【解决方案1】:

只返回参数包中参数的数量。

template<typename ...Args>
unsigned MyFunction(Args... args) {
    return sizeof...(args);
}

int main() {
    return MyFunction(1,2,3);
}

【讨论】:

    【解决方案2】:

    你可以学习和使用variadic templates,如下

    #include <iostream>
    
    template <typename ... Types>
    size_t func(Types ... args){
    
        return sizeof...(args);
    }
    
    int main()
    {
        std::cout << func(1, 2, 3, 4);
    }
    

    【讨论】:

    • 如果Args 是像args 这样的小写字母会更好,因为它是一个变量而不是类型。
    猜你喜欢
    • 2015-02-16
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-03
    • 2023-01-04
    • 2015-12-12
    相关资源
    最近更新 更多