我在一个非常简单的代码上遇到了一个我无法修复的非常奇怪的错误。
我定义了以下函数对象:
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);
}
};
这里是类 Point<n>
在存储 n
之前定义明确n
中一个点的坐标维空间(具有所需的运算符,...)。
我希望得到一个点的 l2 范数 p
(例如创建为 Point<5> p
)使用 L2Norm<5>(p)
.但这给了我以下错误:
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>&’
我很确定我犯了一个非常愚蠢的错误,但我找不到错误的地方!
附言作为附带问题,如果我能说 L2Norm(p)
会更好只有并且编译器检测来自 p
的模板参数但据我所知,这是不可能的。我说得对吗?
最佳答案
您需要创建一个实例并调用其运算符()
。当前您正在尝试调用一个不存在的转换构造函数。
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 { .... }
};
关于c++ - 如何在 C++ 中正确定义函数对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19092415/