0

I'm trying to implement scalar product in C++ inside a library:

namespace Foo
{
    double operator* (vector<double> left, vector<double> right)
    {
        ...
    }
}

But I'm having problems calling it inside the main program. Calling

int main (void)
{
    ...
    double result = Foo::operator* (l, r);
    ...
}

isn't a good solution, while:

int main (void)
{
    ...
    double result = l * r; //l, r are vector<double>
    ...
}

isn't working.

using namespace Foo is considered a bad practice for global usage.

What is a good way to call my operator* fuction inside main scope?

Community
  • 1
  • 1
Blex
  • 156
  • 11

1 Answers1

3

I'm not going to comment too much if you should overload the * operator like this. All I'm going to say is that it will confuse a lot of people.

You can bring in just the operator instead of the whole namespace.

using Foo::operator*;
double result = l * r;

For custom classes you can use ADL (Argument Dependent Lookup), like below:

namespace Foo
{
    struct dvector : public vector<double> 
    { };

    double operator*(dvector left, dvector right)
    {
        return 0;
    }
}

int main (void)
{
    Foo::dvector l, r;
    double result = l * r;
    return 0;
}
Daniel Dinu
  • 1,783
  • 12
  • 16