c++ - 模板中的异常

标签 c++ templates exception

我尝试编译这段代码,但没有收到任何投诉。但是,当我运行它时,它给我最后一行的异常错误,即 cout<<"Norm:"<

你能指导我如何解决这个问题吗?提前谢谢你

#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++ - 模板中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15011529/

相关文章:

c++ - 我可以在不分配内存或复制数据的情况下构造一个对象吗?

c++ - 如何应对 int 溢出

c++ - 无法将虚函数移到 header 之外

python - django 在模板中显示上下文数据而不通过 url 调用 View

exception - 如何在 HSQLDB 过程或函数中引发异常

Java异常处理习语...谁说的对,怎么处理?

非顺序任务中的 Java 异常处理(模式/良好实践)

c++ - 需要帮助在 OpenGL 中移动相机

c++ - CRTP 和基类定义的类型的可见性

c++ - 带有对 type_info 的引用的 std::common_type