kMa*_*ter 4 c++ templates 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);
}
};
Run Code Online (Sandbox Code Playgroud)
这里的类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>&’
Run Code Online (Sandbox Code Playgroud)
我很确定我犯了一个非常愚蠢的错误,但我找不到哪里!
PS作为一个附带问题,如果我只能说L2Norm(p)并且编译器检测到模板参数会更好,p但据我所知,这是不可能的.我对吗?
您需要创建一个实例并调用其运算符().目前,您正在尝试调用不存在的转换构造函数.
return L2Norm<n>()(p-q); // C++03 and C++11
// ^^
Run Code Online (Sandbox Code Playgroud)
要么
return L2Norm<n>{}(p-q); // c++11
// ^^
Run Code Online (Sandbox Code Playgroud)
顺便说一下,您可能也想要调用操作符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 { .... }
};
Run Code Online (Sandbox Code Playgroud)