[英]Is there an easier way to do a macro to define a function with variable amount of arguments?
[英]Is it possible to define the amount of arguments in a function with variable number of arguments by a global variable
我想用一個可變數量的參數定義一個函數,該數量應該由一個全局變量N
來固定,我想到了使用va_list來實現。 是否可以在不引用參數數量的情況下聲明該函數,從而在調用該函數時不必輸入N
作為第一個變量,而只需輸入其余變量? 如果不是,除了使用va_list之外,還有其他方法嗎?
現在,我只是按照標准方法對其進行了聲明,並在其定義中將N
的值分配給該函數的第一個參數(因此,無論哪個整數用作第一個參數,它始終具有所需的值)。 有沒有更優雅的方式?
不知道您想要什么。
但是,如果您至少可以使用C ++ 11,並且如果您接受對可變數量的參數使用可變參數模板,那么我建議使用SFINAE強制將可變數量的參數指定為N
以下是完整的工作示例
#include <type_traits>
static constexpr std::size_t N = 3U;
template <typename ... Args>
typename std::enable_if<N == sizeof...(Args), int>::type foo (Args ... as)
{ return 0; }
int main ()
{
//foo(0, 1); // compilation error
foo(0, 1, 2); // compile
//foo(0, 1, 2, 3); // compilation error
}
max66是對原始問題的正確答案:如何擁有可變數量的參數並限制參數數量。
但是,函數參數的數量在編譯時至關重要。 你可能想要的是類型的一個參數std::vector
。 std::vector
包含可變數量的相同類型的值。 如果要在運行時設置該長度應始終為多少,則可能需要檢查該長度並在錯誤的情況下引發異常。
size_t N__ = 4;
int sum(const std::vector<int>& vec) {
if (vec.size() != N__) { throw std::length_error("error message"); }
int out = 0;
for (int i_ : vec) { out += i_; }
return out;
}
然后你可以用
const int just_ten = sum({1, 2, 3, 4});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.