C++ function pointer


template <typename ValueType>
struct funcPtr
{
    typedef ValueType (*func)(const ValueType, const ValueType);
};

template <typename ValueType>
ValueType add(
    const ValueType a,
    const ValueType b
)
{
    return a+b;
}

template <typename ValueType>
ValueType sub(
    const ValueType a,
    const ValueType b
)
{
    return a-b;
}

template <typename ValueType>
ValueType mul(
    const ValueType a,
    const ValueType b
)
{
    return a*b;
}

template <typename ValueType>
ValueType div(
    const ValueType a,
    const ValueType b
)
{
    return a/b;
}

int main(void)
{
    funcPtr<float>::func fp[4];
    fp[0] = add;
    fp[1] = sub;
    fp[2] = mul;
    fp[3] = div;
    float a = 3.0f, b = 4.0f;
    for(int n = 0; n < 4; ++n)
    {
        std::cout << "fp[" << n << "] = " << fp[n](a,b) << std::endl;
    }
    std::vector< funcPtr<int>::func > fp2;
    fp2.push_back(add);
    fp2.push_back(sub);
    fp2.push_back(mul);
    fp2.push_back(div);
    for(int n = 0; n < fp2.size(); ++n)
    {
        std::cout << "fp2[" << n << "] = " << fp2[n](13,5) << std::endl;
    }

    return 0;
}

Advertisements

One thought on “C++ function pointer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s