简体   繁体   中英

C++ ::std::enable_if and virtual

I've had a scan for answers but ... they seem to be silly questions.

I am perfectly happy with and fully understand (I can't stress that enough) with why it makes no sense to have a template virtual member of a class.

Consider the abstract base class List (With... LinkedList and ArrayList deriving from it)

If the type the list stores has a concept of identity (not a string or int, something without any sensible "==", I wont bring POD up here) you would want a method
virtual bool contains(T& what) const; and
virtual int index(T& what) const;
however if it is a type without identity, like strings or numbers you would want:
virtual int countOccurrences(T& what) const; and
virtual int find(T& what, int occurrence=0) const;

Say.

This cannot be done using ::std::enable_if so you must do something like:

template<class T, bool HAS_IDENTITY> class List;
template<class T> class List<false> {
    virtual int countOccurrences(T& what) const=0;
    virtual int find(T& what, int occurrence=0) const=0;
    /*other stuff*/
};

template<class T> class List<true> {
    virtual bool contains(T& what) const =0;
    virtual int index(T& what) const =0;
    /*other stuff*/
};

This isn't that bad, but there is a lot of code duplication, and I only get wet (against DRY) when I have to.

If I hide the common code in a base class it is a bit nicer.

My question involves scaling with this approach, here we have one bool, giving 2 specialisations, suppose I have n bools then there are 2^n specialisations, I can't see a case where I'd need more than 4, but that is still 16 classes involved! 8 for 3, it's not very nice.

Suppose I have an enum and a bool, then I have 2*enum count specialisations.

It grows far to quickly.

Previously we've used macros to define classes and it'd use the ## operator in the class name to essentially mangle it as a template would. I must say though I quite like enable_if and friends now though...

Is there a pattern someone can show me that'd solve this?

Just a q&d hack, but it should provide some hints.

I somehow know that one could even get rid of that ugly "Dummy" param, but I don't see that right now

EDIT Jul 6th

I made that ansatz a little more seamless to use. A compile-time test of the Concept "Identity", what the question opener is apparently aiming at, would require compile-time testing of

//T t1, t2;
(t1 == t2) == (&t1 == &t2);

and that is imo not possible. Thus I introduced the notion of Feature lists for easy manual assignment of such features.

#include <iostream>
#include <typeinfo>
#include <type_traits>
#ifdef __GNUG__
#include <cxxabi.h>
auto type_str = [](const std::type_info& ti) {
    int stat;
    return abi::__cxa_demangle(ti.name(), 0, 0, &stat);
};
#else 
#warning untested
auto type_str = [](const std::type_info& ti) {
     return ti.name();
};
#endif


typedef int Feature;

const Feature HAS_IDENTITY = 1;
const Feature HAS_FOOBAR = 2;
const Feature HAS_NO_IDENTITY = -HAS_IDENTITY;
const Feature HAS_NO_FOOBAR = -HAS_FOOBAR;
const Feature _TERM_ = 0;


template<typename T, Feature F>
struct has_feature : std::false_type {};

template<int N , int M>
struct is_greater {
    constexpr static bool value = N > M;
};

namespace  detail {
    template<class T, Feature... Fs> struct List {};  // primary template
    template<class T, Feature F>
    struct List<T,F> {};

    template<class T, Feature F, Feature... Fs> 
    struct List<T,F,Fs...> 
        : virtual public 
                std::conditional<
                    has_feature<T,F>::value,
                    List<T, F>,
                    List<T, -F> 
                >::type,
        virtual public 
                std::conditional<
                    is_greater<sizeof...(Fs),0>::value,
                    List<T, Fs...>, 
                    List<T, _TERM_>
                > ::type {};

    template<class T> struct List<T, _TERM_> {};

    template<class T> 
    struct List<T,HAS_NO_FOOBAR> {
        virtual std::string hello() const /* = 0;*/ {
            return std::string("\"What the foo is FOOBAR?\", askes ") + type_str(typeid(T));
        }
    };

    template<class T> 
    struct List<T,HAS_FOOBAR> {
        virtual std::string hello() const /* = 0;*/ {
            return std::string("\"For sure I'm FOOBAR\", says ") + type_str(typeid(T));
        }
    };


    template<class T> 
    struct List<T,HAS_NO_IDENTITY> {
        virtual int index(const T& what) const /* = 0;*/ {
            return 137;
        }
    };

    template<class T> 
    struct List<T,HAS_IDENTITY> {
        virtual int index(const T& what) const /* = 0;*/ {
            return 42;
        }
    };

    template<typename T>
    using Feature_Aware_List = List<T,HAS_IDENTITY,HAS_FOOBAR, /* all Features incuding*/_TERM_>;
} //namespace detail

template<typename T>
using List = detail::Feature_Aware_List<T>;

struct Gadget { 
    bool operator== (const Gadget& rhs) const {
        return this == &rhs;
    }
};     

struct Gimmick { 
    bool operator== (const Gimmick& rhs) const {
        return this == &rhs;
    }
};     

template<Feature F>
struct FeatureList {};

template<>
struct FeatureList<HAS_IDENTITY>
    : public Gadget, 
      public Gimmick 
      /**/ 
{};

#include <valarray>
template<>
struct FeatureList<HAS_FOOBAR>
    : public std::valarray<float> 
      /**/ 
{};

template<class T> 
struct has_feature<T, HAS_IDENTITY> 
    : public std::conditional<
        std::is_base_of<T, FeatureList<HAS_IDENTITY>>::value,
        std::true_type,
        std::false_type
    >::type {};

template<class T> 
struct has_feature<T, HAS_FOOBAR> 
    : public std::conditional<
        std::is_base_of<T, FeatureList<HAS_FOOBAR>>::value,
        std::true_type,
        std::false_type
    >::type {};


int main() {
    List<Gadget> l1 ;
    List<std::valarray<float>> l2;
    std::cout << l1.hello() << " #" << l1.index(Gadget()) << std::endl;
    std::cout << l2.hello() << " #" << l2.index(std::valarray<float>()) << std::endl;

}

Output:

"What the foo is FOOBAR?", askes Gadget #42
"For sure I'm FOOBAR", says std::valarray<float> #137

It should be self-explaining that no specific "list" functionality is implemented, that's mock-only

You may use template policies:

template<class T, bool HAS_IDENTITY> class ListIdentityPolicy;
template<class T> class ListIdentityPolicy<T, false> {
    virtual int countOccurrences(T& what) const = 0;
    virtual int find(T& what, int occurrence = 0) const = 0;
};
template<class T> class ListIdentityPolicy<T, true> {
    virtual bool contains(T& what) const = 0;
    virtual int index(T& what) const = 0;
};

template<class T, bool HAS_FOOBAR> struct ListFoobarPolicy;
template<class T> struct ListFoobarPolicy<T, false> {
    virtual void foo() = 0;
};
template<class T> struct ListFoobarPolicy<T, true> {
    virtual void bar() = 0;
};

template <class T> class List
    : public ListIdentityPolicy<T, HasIdentity<T>::value>
    , public ListFoobarPolicy<T, HasFoobar<T>::value>
{
public:
    /*other stuff*/
};

HasIdentity and HasFoobar are type traits which you would define, each containing a static const bool value indicating whether T has the corresponding property.


Or, you could give List a non-virtual public API, and hide the dynamic dispatch in the implementation:

template <class T> class List
{
public:
    enum Impl {
        LinkedList = 0,
        ArrayList,
    };
    List(Impl i) : pimpl(makePimpl(i)) {}
    List(List const& other) : pimpl(other.pimpl->clone())
    List& operator=(List const& other) { pimpl = other.pimpl->clone(); }

    int count(T& what) const
    { static_assert(! HasIdentity<T>::value, "oops"); return pimpl->count(what); }
    int find(T& what, int n = 0) const
    { static_assert(! HasIdentity<T>::value, "oops"); return pimpl->find(what, n); }
    bool contains(T& what) const
    { static_assert(HasIdentity<T>::value, "oops"); return pimpl->contains(what); }
    int index(T& what) const
    { static_assert(HasIdentity<T>::value, "oops"); return pimpl->index(what); }
    void foo()
    { static_assert(! HasFoobar<T>::value, "oops"); pimpl->foo(); }
    void bar()
    { static_assert(HasFoobar<T>::value, "oops"); pimpl->bar(); }

private:
    struct AbstractPimpl
    {
        virtual std::unique_ptr<AbstractPimpl> clone() const = 0;
        virtual int count(T& what) const = 0;
        virtual int find(T& what, int n = 0) const = 0;
        virtual bool contains(T& what) const = 0;
        virtual int index(T& what) const = 0;
        virtual void foo() = 0;
        virtual void bar() = 0;
    };

    struct LinkedListPimpl : public AbstractPimpl
    {
        std::unique_ptr<AbstractPimpl> clone() override;
        int count(T& what) const override;
        int find(T& what, int n = 0) const override;
        bool contains(T& what) const override;
        int index(T& what) const override;
        void foo() override;
        void bar() override;
        /* ... */
    };

    struct ArrayListPimpl : public AbstractPimpl
    {
        std::unique_ptr<AbstractPimpl> clone() override;
        virtual int count(T& what) const override;
        virtual int find(T& what, int n = 0) const override;
        virtual bool contains(T& what) const override;
        virtual int index(T& what) const override;
        virtual void foo() override;
        virtual void bar() override;
        /* ... */
    };

    std::unique_ptr<AbstractPimpl> pimpl;

    static std::unique_ptr<AbstractPimpl> makePimpl(Impl i) {
        switch (i) {
            LinkedList: default:
            return std::make_unique<LinkedListPimpl>();
            ArrayList:
            return std::make_unique<ArrayListPimpl>();
        }
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM