模板中出现异常
Exception in template
本文关键字:异常 更新时间:2023-10-16
我试图编译这段代码,但没有收到任何抱怨。然而,当我运行它时,它会在最后一行给我一个异常错误,即cout<lt;"标准:"<
你能指导我如何解决这个问题吗。提前感谢
#include <stdafx.h>
#include <iostream>
#include <string>
#include <boost/function.hpp>
#include <boost/array.hpp>
using namespace std;
template<typename R,typename D>
class GenericFunction
{
private:
boost::function<R (D)> f;
protected:
GenericFunction(){};
public:
GenericFunction(const boost::function<R (D)>& myFunction){f=myFunction;};
R evaluate(const D& value) const{cout<<"Good Job"<<endl;} ;
R operator ()(const D& value);// const{ return f(value); };
};
template <typename R, typename D, int N>
class ScalarValuedFunction:public GenericFunction<R,boost::array<D, N>>
{
public:
ScalarValuedFunction(const boost::function<R (const boost::array<D, N>)> &myF){};
};
template<typename Numeric, std::size_t N>
Numeric Norm(const boost::array<Numeric , N>& Vec)
{
Numeric Result=Vec[0]*Vec[0];
for (std::size_t i=1; i<Vec.size();i++)
{
Result+=Vec[i]*Vec[i];
}
return Result;
}
double test(double t)
{
return t;
}
int main ()
{
const int N=4;
boost::array<double, N> arr={0.2, .3, 1.1, 4};
ScalarValuedFunction<double, double, N> myfun(Norm<double,N>);
cout<<"Norm:"<<myfun(arr)<<endl;
}
您没有将函数参数转发到基类的构造函数:
ScalarValuedFunction(const boost::function<R (const boost::array<D, N>)> &myF)
: GenericFunction<R, boost::array<D, N>>(myF) // <=== ADD THIS
{
} //; <== SEMICOLON NOT NEEDED AFTER A FUNCTION DEFINITION!
如果不这样做,GenericFunction
子对象将被初始化为默认构造函数(派生类可以访问该构造函数,因为它被声明为protected
),其成员变量f
也将被默认初始化。
然后,当试图在operator ()
(我想它的定义就是您在评论中显示的定义)中调用它时,Ka Boom。
相关文章:
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 为什么异常不退出程序?
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 是什么导致了Unity 3D中的"错误线程异常"?
- 如何将strftime中的格式错误作为异常捕获
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 尝试使用智能指针时引发异常
- 函数如何通知用户它基于函数原型抛出异常?
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Pytorch torch.cholesky忽略异常