Run-time check for template function existance

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Patrick Kowalzick

    Run-time check for template function existance

    Hello all,

    I want to test run-time if a template function for a special type exists.
    See example below. The checkfoo function is where I need some hints.

    Regards,
    Patrick


    #include <iostream>

    template <typename> struct fooclass;

    template <> struct fooclass<int>
    {
    static void huhu()
    {
    std::cout << "int" << std::endl;
    }
    };

    template <> struct fooclass<long>
    {
    static void huhu()
    {
    std::cout << "long" << std::endl;
    }
    };

    template <typename T> void foo()
    {
    fooclass<T>::hu hu();
    }

    template <typename T> bool checkfoo()
    {
    if ( foo<T>() ) return true; // check for existance here
    else return false;
    }


    int main()
    {
    foo<int>();
    foo<long>();

    checkfoo<int>() ; // should return true
    checkfoo<double >(); // should return false

    return 0;
    }




  • Chris Theis

    #2
    Re: Run-time check for template function existance


    "Patrick Kowalzick" <Patrick.Kowalz ick@cern.ch> wrote in message
    news:bii7od$cv8 $1@sunnews.cern .ch...[color=blue]
    > Hello all,
    >
    > I want to test run-time if a template function for a special type exists.
    > See example below. The checkfoo function is where I need some hints.
    >
    > Regards,
    > Patrick
    >[/color]
    [SNIP]

    Hi Patrick,

    the whole thing is not as trivial as it might seem. In principle the
    compiler looks for instantiations of templates for a specific type and
    writes code for this type. This means that there will only be code for types
    that are actually used. Actually that's one of the big advantages of
    templates because it will prevent code - bloating. Also in the context of
    incomplete instatiation one sees the true power of this concept, though that
    would lead too far here.

    Anyway this means that there is no easy way to do the checking during
    runtime but you could do it during compile time. IMHO compile time checks
    are anyway better than runtime checks because it's up to the implementer to
    decide how/what to fix but the runtime error will occur at the client side
    :-)
    If you still want to stick to runtime checks you can register all your
    functions in a map and check whether an appropriate function is available.

    Hope that helps
    Chris


    Comment

    Working...