I have a piece of code which does something like this:
void some_func(SomeType st) {
some_stuf...
dosomething( st.myStruct() );
some_more_stuff...
}
This SomeType::myStruct is of type MyStruct. This SomeType goes through some serialization, and on the other side of communication channel I get deserialized SomeType which is called AlmostSomeType which has the same fields, except that myStruct is of type std::string (it couldn't be deserialized to MyStruct).
MyStruct can be created from std::string.
Now, to not create additional versions of some_func (DRY!) I'm going to do this:
template< typename Type >
void some_func( Type type ) {
some_stuf...
dosomething( getMyStruct( type.myStruct() ) );
// or even something like:
const MyStruct& myStruct = getMyStruct( type.myStruct() );
more calls to myStruct...
some_more_stuff...
}
where getMyStruct looks like this:
template< typename T >
T getMyStruct( T&& aT )
{ return aT; }
MyStruct getMyStruct( std::string myStructString )
{ return MyStruct( myStructString ); }
Now here's what I know/think :
- I know it doesn't look nice, but real-life project's don't look nice. I cannot modify
AlmostSomeTypeandSomeType. - I do not want to create any additional overhead, that's why I used universal reference which will handle any type of
MyStruct(reference, const reference, etc), andstd::stringversion for strings. - Flaws? If someone will put anything else than
MyStructorstd::stringintogetMyStructit might pass if parameter-constructors ofMyStructaren'texplicit. - I've done simple tests with
MyStructconsisting of all the needed ctors and assignment operators, compiled code with-O2and got the results I expected, i.e. no copy-ctors called.
I'd like to hear your opinions if this is the right way, i.e. if this function template approach is OK or are there some caveats I should be aware of. I know that I'm counting a bit on compilers optimizations, but hey! You cannot depend only on language semantics.
Environment: gcc (4.7.2), -std=c++11, -O2
Aucun commentaire:
Enregistrer un commentaire