I want to make a factory function template that can be called with a fixed number of parameters, each parameter type a template parameter. With two parameters :
template< typename T1, typename T2 >
and_implementation< T1, T2 > and( T1 && p1, T2 && p2 ){
return and_implementation< T1, T2 >( p1, p2 );
}
In the and_implementation
object I want to store a reference to each parameter that is an lvalue, and a copy of each parameter that is an rvalue. I don't want to use the heap.
The goal is that when I write
auto p1 = ....
auto p2 = ....
auto p3 = and( p1, p3 );
the p3
object contains only references to p1
and p2
, but when I write something like
auto p1 = ....
auto p2 = ....
auto p3 = ....
auto p4 = and( p1, and( p2, p3 ));
the p4
object contains a referencde to p1
, but a copy of and(p2, p3)
.
Is there a way to do this?
What I came up with (the factory is called invert and has only one parameter) is
template< typename T >
struct invert_impl: public gpio {
T pin;
template< typename TT > invert_impl( TT && p ):
pin( p ) {} // this is line 60
};
template< typename P >
invert_impl< P > invert( P && pin ){
return invert_impl< P >( pin );
}
This works for
autp pin4 = lpc_gpio< 4 >{};
auto led = invert( pin4 );
but for
autp pin4 = lpc_gpio< 4 >{};
auto led = invert( invert( pin4 ));
I get (GCC 4.9.3):
main.cpp:60:14: error: invalid initialization of reference of type 'lpc_gpio<4>&' from expression of type 'invert_impl<lpc_gpio<4>&>'