user13540365
user13540365

Reputation:

Specific Friend Function Specialization

Suppose I have a class like follows:

namespace n
{
    template<class integral>
    class ex
    {
    public:
        friend auto ::operator +(integral i,
                                 ex const & e)
        {
            return i + e.i;
        }
        int i;
    }
}

This code does not work because operator + is not in the global namespace.

What can be done to allow this inline, immediate definition? I'd like to do this without declaring a global templated operator + and then declaring the friend as a seperate templated function?

namespace n
{
    template<class integral>
    class ex
    {
    public:
        template<class operator_integral> // redundant
        friend auto ::operator +(operator_integral i,
                                 ex<operator_integral> const & e); // longer
        //{
        //  return i + e.i; // can no longer define here
        //}
        int i;
    }
}

template<class operator_integral> // AGAIN
auto operator +(operator_integral i,
                ex<operator_integral> const & e); // AGAIN AGAIN
{
    return i + e.i; // definition is now far away
}

Upvotes: 0

Views: 40

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409364

In the first example, because of Argument Dependent Lookup (ADL) it will work fine if you just drop the scope operator from the friend declaration:

namespace n
{
    template<class integral>
    class ex
    {
    public:
        // Note lack of scope operator in declaration
        friend auto operator +(integral i,
                               ex const & e)
        {
            return i + e.i;
        }
        int i;
    }
}

Can be used as e.g.:

n::ex<int> x;
auto r = 12 + x;

No using directive needed.

Upvotes: 2

Related Questions