可変個引数リスト (...) (C++/CLI)
可変個の引数を持つ関数を実装する方法に ... Visual C++の構文を使用する方法を次の例に示します。
... を使用するパラメーターは、パラメーター リストの最後のパラメーターにする必要があります。
例
コード
// mcppv2_paramarray.cpp
// compile with: /clr
using namespace System;
double average( ... array<Int32>^ arr ) {
int i = arr->GetLength(0);
double answer = 0.0;
for (int j = 0 ; j < i ; j++)
answer += arr[j];
return answer / i;
}
int main() {
Console::WriteLine("{0}", average( 1, 2, 3, 6 ));
}
出力
3
コード例
次の例では、Cから引数の数が可変であるVisual C++の関数を呼び出す方法を示します。
// mcppv2_paramarray2.cpp
// compile with: /clr:safe /LD
using namespace System;
public ref class C {
public:
void f( ... array<String^>^ a ) {}
};
可変個の引数を受け取ることができるのは、関数のように、関数 f は、CやVisual Basicなどから呼び出すことができます。
では、C、ParamArray のパラメーターに渡される引数は、可変個の引数で呼び出すことができます。次のコード例は、Cにあります。
// mcppv2_paramarray3.cs
// compile with: /r:mcppv2_paramarray2.dll
// a C# program
public class X {
public static void Main() {
// Visual C# will generate a String array to match the
// ParamArray attribute
C myc = new C();
myc.f("hello", "there", "world");
}
}
Visual C++の f の呼び出しが初期化された配列または可変長配列を渡すことができます。
// mcpp_paramarray4.cpp
// compile with: /clr
using namespace System;
public ref class C {
public:
void f( ... array<String^>^ a ) {}
};
int main() {
C ^ myc = gcnew C();
myc->f("hello", "world", "!!!");
}