How to correctly define function objects in C ++?

I get a very strange error in a very simple code that I could not fix.

I defined the following function object:

template<const size_t n> class L2Norm {
    public:
            double operator()(const Point<n>& p) {
                /* computes the L2-norm of the point P ... */

            }
            double operator()(const Point<n>& p,
                            const Point<n>& q) {
                    return L2Norm<n>(p-q);
            }
};

Here the class is Point<n>correctly defined earlier in order to preserve the coordinates of the npoint in n-dimensional space (with the required operators, ...).

I expect to get the l2-norm of a point p(created, for example Point<5> p) using L2Norm<5>(p). But this gives me the following error:

no matching function for call to ‘L2Norm<5ul>::L2Norm(Point<5ul>&)’
note: candidates are: L2Norm<n>::L2Norm() [with long unsigned int n = 5ul]
note:   candidate expects 0 arguments, 1 provided
note: L2Norm<5ul>::L2Norm(const L2Norm<5ul>&)
note:   no known conversion for argument 1 from ‘Point<5ul>’ to ‘const L2Norm<5ul>&’

I'm sure I'm making a very dumb mistake, but I can’t find out where!


PS As a side issue, it would be much better if I could only say L2Norm(p), and the compiler found a template parameter from p, but as far as I know, this is not possible. I'm right?

+4
2

(). .

return L2Norm<n>()(p-q); // C++03 and C++11
//              ^^

return L2Norm<n>{}(p-q);  // c++11
//              ^^

, const, , :

template<const size_t n> class L2Norm 
{
 public:
  double operator()(const Point<n>& p) const { .... }
  double operator()(const Point<n>& p, const Point<n>& q) const { .... }
};
+7

@juanchopanza, :

L2Norm<5>()(p-q);

:

L2Norm()(p-q)

" ". operator():

class L2Norm {
public:
    template<const size_t n> 
    double operator()(const Point<n>& p) const {
        /* computes the L2-norm of the point P ... */
    }
    template<const size_t n> 
    double operator()(const Point<n>& p,
                      const Point<n>& q) const {
        return operator()(p-q);
    }
};

, ++ 03, ++ 03. boost , , ++ 11 , decltype.

():

class {
public:
    template<const size_t n> 
    double operator()(const Point<n>& p) const {
        /* computes the L2-norm of the point P ... */
    }
    template<const size_t n> 
    double operator()(const Point<n>& p,
                      const Point<n>& q) const {
        return operator()(p-q);
    }
} L2Norm;

L2norm(p-q); // Uses the object L2Norm, which has an unnamed type.
+2

All Articles