469,270 Members | 1,764 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,270 developers. It's quick & easy.

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>::huhu();
}

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;
}


Jul 19 '05 #1
1 2550

"Patrick Kowalzick" <Pa***************@cern.ch> wrote in message
news:bi**********@sunnews.cern.ch...
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

[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
Jul 19 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

13 posts views Thread by Bob Day | last post: by
3 posts views Thread by emman_54 | last post: by
9 posts views Thread by Brett Wesoloski | last post: by
8 posts views Thread by David Thielen | last post: by
3 posts views Thread by traceable1 | last post: by
7 posts views Thread by mxdevit | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.