Re: enable_if and pure virtual functions
Am 12.01.2012 20:48, schrieb kelvSYC:
I'm kind of confused on how enable_if and virtual functions work
together. Suppose you have this:
(using your favourite implementation of enable_if here)
template<class T>
struct DerivedProperty;
template<class T>
class AbstractBase { // CRTP, as you can't mix "virtual" and
"function template", it would appear... or can you?
Yes, you cannot declare a function template that is a virtual function.
virtual enable_if<DerivedProperty<T>, int>::type doSomething() =
0;
};
This is an absolutely useless application of enable_if - and this has nothing to do with virtual functions. In your example the declaration of doSomething() will be instantiated once AbstractBase<U> will be instantiated for some type U making the instantiation of AbstractBase<U> potentially ill-formed (depending on U). The only reason for such a construction would be to act as some convoluted form of static assertion that would better be written as
template<class T>
class AbstractBase {
static_assert(DerivedProperty<T>::value, "DerivedProperty not satisfied");
virtual int doSomething() = 0;
};
instead. If you want to declare a virtual function depending on some constraints, it is better to do that via a base-class switch, e.g.
template<class T, bool = DerivedProperty<T>::value>
class AbstractBase {
virtual int doSomething() = 0;
};
template<class T>
class AbstractBase<T, false> {};
Also, would something similar apply if the enable_if was instead a
parameter instead of the return type?
This would not change anything, because in either situation the declaration of the function could be ill-formed.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]