4

この名前空間の外から名前空間で宣言された関数を呼び出すときは、通常、明示的に名前空間のプレフィックスを付ける必要があります。

namespace ns1 {
    void myfunc();
}

myfunc();        // compiler complains
ns1::myfunc();   // good

ただし、コンパイラが使用する関数を自動的に考案できるように見えるこの状況があります。

namespace mymath {
    struct Vector3 {
        float x, y, z;
    };
    Vector3 vector_cross(const Vector3& lhs, const Vector3 &rhs)
    {
        return lhs; // Pretend this is a cross product
    }
} // ns

int main(int argc, char** argv)
{
    mymath::Vector3 v, w, x;
    x = vector_cross(v, w);   // <---- Here, I do not need to
                              //       prefix with the namespace
    return 0;
}

Q1: コンパイラが引数の型に基づいて適切な関数を自動的に選択できるためですか? または、他の何か?


さらにテストした結果、別の名前空間に同じ宣言を持つ別の関数を追加しても、コンパイラは文句を言わないことがわかりました。

namespace mymath {
    // same as above
} // ns

namespace math2 {
    mymath::Vector3 vector_cross(const mymath::Vector3& lhs, const mymath::Vector3 &rhs)
    {
        return rhs; // Return rhs this time
    }
} // ns

int main(int argc, char** argv)
{
    mymath::Vector3 v, w, x;
    x = vector_cross(v, w);   // <---- Here, which one did the compiler chose?
    return 0;
}

Q2: この動作を無効にするにはどうすればよいですか?

編集: 私のコンパイラ:gcc version 4.7.2 (Debian 4.7.2-5)

4

1 に答える 1