The commented code works, but it is not a reference, so it has more computational cost.
void CClass::Function(const CArray<CItem*>* ItemsInput) const
{
/*
CArray<CItem*> Items;
if (ItemsInput != nullptr)
Items.Copy(*ItemsInput);
else
GetContainer().GetInnerItems(Items, NULL, true);
*/
const CArray<CItem*>& Items=
(ItemsInput!= nullptr)?
*ItemsInput
:
[this] () -> const CArray<CItem*>
{
CArray<CItem*> InnerItems;
GetContainer().GetInnerItems(InnerItems, NULL, true);
return const_cast <const CArray<CItem*>& > (InnerItems);
}
;
//...
}
The uncommented code is the maximal extent where I got trying to use an approach of ternary operator and lambda expression, but until now it was unsuccessful, giving the error:
1>Class.cpp(line of the last semicolon): error C2446: ':' : no conversion from '`anonymous-namespace'::<lambda2>' to 'const CArray<TYPE>'
1> with
1> [
1> TYPE=CItem *
1> ]
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
Important things to notice:
- I pass
this
on the lambda capture, just to have access to theGetInnerItems
method - The
GetInnerItems
method gives the inner items via its first parameter of typeCArray<CItem*>&
, which is non-const and could never be const.
Therefore, it seems to me the problem is the way the GetInnerItems
works and has nothing to do with ternary operator. Assume I can not change its signature to return a CArray
, because CArray
is derived from CObject
which declares:
class AFX_NOVTABLE CObject
{
//...
private:
CObject(const CObject& objectSrc); // no implementation
void operator=(const CObject& objectSrc); // no implementation
//...
}
So, questions are:
How can I assign the alternative value to the reference-to-const
Items
variable keeping const-correctness?If you successfully answered the first question using a
const_cast
, can you now give a solution without it?