Run-time check for template function existance

P

Patrick Kowalzick

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

Chris Theis

Patrick Kowalzick said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top