By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,369 Members | 1,138 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,369 IT Pros & Developers. It's quick & easy.

Run-time check for template function existance

P: n/a
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
Share this Question
Share on Google+
1 Reply


P: n/a

"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.