tags:

views:

110

answers:

1

Hi2All..

I have some null struct, for example:

struct null_type
{
    null_type& someNonVirtualMethod()
    {
        return *this;
    }
};

And in some function i need to pass reference to this type. Reason:

template <typename T1 = null_type, typename T2 = null_type, ... >
class LooksLikeATupleButItsNotATuple
{
public:
    LooksLikeATupleButItsNotATuple(T1& ref1 = defParamHere, T2& ref2 = andHere..) 
        : _ref1(ref1), _ref2(ref2), ...
    {
    }

    void someCompositeFunctionHere()
    {
        _ref1.someNonVirtualMethod();
        _ref2.someNonVirtualMethod();
        ...
    }

private:
    T1& _ref1; 
    T2& _ref2; 
    ...;
};

It is a good practice to use null reference as a default parameter?:

*static_cast<NullType*>(0)

It works on MSVC, but i have some doubts...

+7  A: 

Any attempts to create a null-reference result in undefined behavior. So, it is never a good practice, even if it might seem to "work".

If you really need to have a reserved value for a default parameter of reference type, declare a "dummy" object of corresponding type and use it as default value for your references.

AndreyT
or use a pointer instead of reference.
jalf
You could inherit `LooksLikeATup...` from `null_type` and initialize the not used references with `*this`.
Johannes Schaub - litb