出典: フリー百科事典『ウィキペディア(Wikipedia)』 (2021/12/09 03:43 UTC 版)
「多重定義」の記事における「言語による多重定義のサポート」の解説
関数の多重定義をサポートしない言語では、たとえ関数の引数の型や数によらずアルゴリズムすなわち本質的な内容がまったく同じでも、引数の型や数ごとに関数をそれぞれ定義する場合は同じ名前が使えず、引数に応じた名前をそれぞれ付ける必要があり、呼び出すときも引数に応じて使い分ける必要がある。 C言語での例を以下に示す。 #include #include float vector2f_length(float x, float y) { return sqrtf(x * x + y * y); }double vector2d_length(double x, double y) { return sqrt(x * x + y * y); }float vector3f_length(float x, float y, float z) { return sqrtf(x * x + y * y + z * z); }double vector3d_length(double x, double y, float z) { return sqrt(x * x + y * y + z * z); }int main(void){ printf("%f\n", vector2f_length(1.0f, -1.0f)); printf("%f\n", vector2d_length(1.0, 2.0)); printf("%f\n", vector3f_length(1.0f, -1.0f, 1.0f)); printf("%f\n", vector3d_length(1.0, 2.0, -1.0));} ベクトルの長さを計算する関数を、型および次元ごとに命名している。 一方、関数の多重定義をサポートする言語では、関数のシグネチャが異なれば同じ名前を使うことができる。関数には本質的な名前だけを付ければよく、呼び出すときも引数によらず一様に記述できる。 C++での例を以下に示す。 #include #include float vector_length(float x, float y) { return std::sqrt(x * x + y * y); }double vector_length(double x, double y) { return std::sqrt(x * x + y * y); }float vector_length(float x, float y, float z) { return std::sqrt(x * x + y * y + z * z); }double vector_length(double x, double y, float z) { return std::sqrt(x * x + y * y + z * z); }int main(void){ printf("%f\n", vector_length(1.0f, -1.0f)); // (float, float) バージョンが呼ばれる。 printf("%f\n", vector_length(1.0, 2.0)); // (double, double) バージョンが呼ばれる。 printf("%f\n", vector_length(1.0f, -1.0f, 1.0f)); // (float, float, float) バージョンが呼ばれる。 printf("%f\n", vector_length(1.0, 2.0, -1.0)); // (double, double, double) バージョンが呼ばれる。} なお、C++11規格では、2次元ベクトルの長さを求める標準関数として、多重定義されたstd::hypot()関数が用意されている。C++17では3次元ベクトルバージョンも追加されている。
※この「言語による多重定義のサポート」の解説は、「多重定義」の解説の一部です。
「言語による多重定義のサポート」を含む「多重定義」の記事については、「多重定義」の概要を参照ください。