Question

I have a class like this:

template <class Object = NullObject>
class MyClass : OptimizedStorage<Object> {
...

public:
    //Cannot do this in Visual studio 2012
    template <class Object2 = Object,
              class = enable_if<!is_same<Object2, NullObject>::value>>
    Object & get() const {
        return this->object_;
    }
}

Does anyone know:

  1. A workaround for having this interface.
  2. Some other workaround that even if it makes things a bit more dirty, still allows me to get() my underlying object when it exists.

Regards

Was it helpful?

Solution

A simple workaround is to write a wrapper function which just calls the template. For example:

private:
    template<typename ENABLER>
    Object& get_()
    {
        return this->object_;
    }

    template<typename Object2>
    Object& get_()
    {
        return get_<typename std::enable_if<!std::is_same<Object2,NullObject>::value>::type>();
    }

public:
    //Overload for default Object template parameter:
    Object& get()
    {
        return get_<Object>();
    }

Of course the compiler is cappable of inline all the wrappings, so performance is not a concern here.

Note that I have dopped the const qualifier: You are returning a reference to internal data, that getters cannot/shouldn't be const.

OTHER TIPS

Following may help:

template <class Object = NullObject>
class MyClass {
    Object object_;

    template <class T>
    typename std::enable_if<!std::is_same<T, NullObject>::value, Object &>::type
    get_() { return this->object_; }
public:
    Object& get() { return get_<Object>(); }
};

or you may specialize your struct (that may require some copy/paste :/ ):

template <class Object = NullObject>
class MyClass {
    Object object_;
public:
    Object& get() { return this->object_; }
};

template <>
class MyClass<NullObject> {
public:
    // No get function.
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top