Thread: Pointer to template function workaround

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607

    Pointer to template function workaround

    Since pointers to template functions are not possible in C++ I would like to know how to go about solving the following issue:

    Given the template function:

    Code:
    namespace Math
    {
        class Utils
        {
              template <typename T> static T LinearInterpolate(T value1, T value2, float lerpFactor)
              {
                     return static_cast<T>(value1 + lerpFactor * (value2 - value1));
              }
        }
    }
    To use this function you obviously do:

    Code:
    float floatResult = Math.Utils.LinearInterpolate<float>(10.0f,20.0f,0.5f);
    double doubleResult = Math.Utils.LinearInterpolate<double>(10.0,20.0,5.0f);
    D3DXCOLOR colorResult = Math.Utils.LinearInterpolate<D3DXCOLOR>(D3DXCOLOR(0.0f, 0.0f, 0.0f, 0.0f), D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f), 0.5f);
    However this will be littered throughout my code. If I want to change the type of linear interpolation (IE: cosine interpolation) using this approach I will have to go through the code and change all LinearInterpolate calls to some other template function. However it is nice to have a template function here b/c you can then LinearInterpolate between any type that has the correct operators overloaded which is quite handy.

    It would be nice to simply use a function pointer to Math.Utils.LinearInterpolate which then would mean to alter the function being used I would simply alter what function the pointer pointed to...but b/c it is a template this is not an option.

    Any ideas?

    EDIT: Fixed typo in code that used coef instead of lerpFactor.
    Last edited by VirtualAce; 01-13-2012 at 02:15 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 01-30-2011, 04:28 PM
  2. template parameter on a function that dont use the template
    By underthesun in forum C++ Programming
    Replies: 1
    Last Post: 06-22-2009, 05:38 PM
  3. Specialising a member function with a template template parameter
    By the4thamigo_uk in forum C++ Programming
    Replies: 10
    Last Post: 10-12-2007, 04:37 AM
  4. Replies: 4
    Last Post: 09-07-2006, 01:32 AM
  5. Template Friend Workaround for MSVC?
    By LuckY in forum C++ Programming
    Replies: 1
    Last Post: 04-01-2005, 05:41 PM