Search code examples
c++c++11visual-c++-2012

Workaround for the lack of default template parameters in visual c++ 2012


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


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.