Boost logo

Boost Users :

Subject: [Boost-users] Conditional function definition with boost::enable_if
From: Matthias Vallentin (vallentin_at_[hidden])
Date: 2009-02-10 15:29:15


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 <boost/type_traits/is_function.hpp>
#include <boost/utility/enable_if.hpp>

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_at_[hidden]
http://matthias.vallentin.cc

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net