在尝试为原始函数创建函数对象包装类时,我尝试在头文件的命名空间中定义并在源代码中声明它时遇到了多重定义错误。这很好,但是当我尝试根据命名空间中的原始函数实例化一个函数对象时,我得到了错误。
空间.h
#ifndef SPACE_H
#define SPACE_H
namespace fobj{
class function_object
{
public:
function_object(double (*f)(double)) { raw_function = f; }
double operator()(double x) {return raw_function(x); }
private:
double (*raw_function)(double);
};
}
namespace fraw {
double raw(double x);
/** below is the trouble maker. When removed, the error doesn't occur. But also,
when the above is instead declared inline, the error doesn't occur either. **/
fobj:: function_object obj( raw );
}
#endif
空间.cpp
#include "space.h"
double fraw:: raw(double x) { return x; }
主文件
#include <iostream>
#include "space.h"
int main()
{
std::cout<< fraw::raw(1.5)<<std::endl;
std::cout<< fraw::obj(2.5)<<std::endl;
return 0;
}