vendredi 22 mai 2015

Function for type converting or forwarding (depending on input type)

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 :

  1. I know it doesn't look nice, but real-life project's don't look nice. I cannot modify AlmostSomeType and SomeType.
  2. 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), and std::string version for strings.
  3. Flaws? If someone will put anything else than MyStruct or std::string into getMyStruct it might pass if parameter-constructors of MyStruct aren't explicit.
  4. I've done simple tests with MyStruct consisting of all the needed ctors and assignment operators, compiled code with -O2 and 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