内联函数作为模板参数,不使用函数指针

时间:2017-10-03 08:54:32

标签: c++ templates inline

我正在开发一个对象Foo,它有几个成员变量和一个主要成员函数bar()。

template<typename T>
Foo
{
public:
    T bar()
    {
       ...
       return m_a + myfunction(m_b);
    }

private :
    T m_a, m_b;
};

目前myfunction是另一个成员函数。但我希望能够写出这样的主要内容:

float newfunction(float) {....}

void main()
{
    Foo<float, newfunction> foo;
    float result = foo.bar();
}

所以,newfunction将在bar()中使用inline而不是myfunction。我不想为了性能目的而使用函数指针:bar()使用openMP和myfunction()被设计为每秒被cpu的每个核调用数千次。所以我认为在这种情况下,我的函数必须是内联的,我不能使用指针。新功能是一个简单的功能,计算成本非常低。

1 个答案:

答案 0 :(得分:2)

如果您只在public ActionResult Index(string search) { var tbl_Student1 = db.tbl_Student1.Include(t => t.tbl_Class); return View(tbl_Student1.Where(x => x.LastName.Contains(search) || search == null).ToList()); } 函数中使用newfunction,那么我建议您将其作为参数传递给Foo::bar函数:

bar

然后您可以将其称为

template<typename T>
struct Foo
{
    template<typename F>
    T bar(F func)
    {
        return m_a + func(m_b);
    }

    T m_a, m_b;
};

如果另一方面,您需要存储要在Foo<float> foo; float result = foo(newfunction); 的多个成员函数中使用的函数,我建议您阅读std::function

然后你可以做类似

的事情
Foo

用作

template<typename T>
struct Foo
{
    Foo(std::function<T(T)>& func)
        : m_function(func)
    {}

    T bar()
    {
        return m_a + m_function(m_b);
    }

    T m_a, m_b;
    std::function<T(T)> m_function;
};
相关问题