Reputation: 11
I'm developing an object Foo, which have several member variables and one major member function bar().
template<typename T>
Foo
{
public:
T bar()
{
...
return m_a + myfunction(m_b);
}
private :
T m_a, m_b;
};
At the moment myfunction is another member function. But I would like to be able to write a main like this :
float newfunction(float) {....}
void main()
{
Foo<float, newfunction> foo;
float result = foo.bar();
}
And so, newfunction would be used inline in bar() instead of myfunction. I don't want to use a function pointer for performance purpose : bar() use openMP and myfunction() is designed to be called thousands times per second by each core of the cpu. And so I think that in this condition, my function must be inline and I must not use a pointer. And newfunction is a simple function, with a really low computational cost.
Upvotes: 1
Views: 1208
Reputation: 409482
If you only use newfunction
in the Foo::bar
function, then I suggest you pass it as an argument to the bar
function instead:
template<typename T>
struct Foo
{
template<typename F>
T bar(F func)
{
return m_a + func(m_b);
}
T m_a, m_b;
};
Then you can call it like
Foo<float> foo;
float result = foo(newfunction);
If on the other hand you need to store the function to be used in multiple member functions of Foo
I recommend you read about std::function
.
Then you can do something like
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;
};
To be used as
Foo<float> foo(newfunction);
float result = foo.bar();
Upvotes: 2