Hi folks,
I would like to define a function in a class only if a child defines it.
In the below example, I would like the function f() to exist only in an
object bar if it defines a function i(). So far, my approach with
boost::enable_if failed because bar is not a complete type during
examination. T is clearly incomplete at the time when b is defined.
What would be the correct approach to solve this problem?
#include
#include
template <typename T>
struct foo
{
typename boost::enable_if<
typename boost::is_function<typename T::i>::type, void
>::type
f() { }
};
struct bar : foo<bar>
{
void i() { }
};
int main()
{
bar b;
b.f(); // should only compile since bar defines i()
return 0;
}
enable_if.cc: In instantiation of ‘foo<bar>’:
enable_if.cc:16: instantiated from here
enable_if.cc:10: error: invalid use of undefined type ‘struct bar’
enable_if.cc:16: error: forward declaration of ‘struct bar’
enable_if.cc: In function ‘int main()’:
enable_if.cc:25: error: ‘struct bar’ has no member named ‘f’
Matthias
--
Matthias Vallentin
vallentin@icsi.berkeley.edu
http://matthias.vallentin.cc