mercredi 27 octobre 2021

only enable template function for specified types / disable for any other types

//my_utils.h
namespace A {
 namespace B {
  template <typename T, typename U>
  T encode( U value ) = delete;
  
  template <typename T, typename U>
  U decode( T value ) = delete;

  uint8_t encode( bool value );

  bool decode( uint8_t value );
  .
  .
  .
  //in this same .h file
  template <typename T>
  class X {
    public:
     void func() {
       uint8_t a = encode(bool_var);
     }
  };
 }
}

//myutils.cpp
namespace A {
 namespace B {
  
  uint8_t encode<uint8_t, bool>( bool value ) {
    //do something
  }

  bool decode<uint8_t, bool>( uint8_t value ) {
    //do something
  }

 }
}

It works this way but I was wondering... is this the right way? I was spending quite some time trying to make it work with template specialization but I just couldn't figure it out.For example it works with "const char *" but it's not what my intention was.

My goal was to disable this function for any type other than those I specialized and disable implicit type conversion at the same time.

Any toughts on this? Is there a better practice?

I'm using templates more and more and I really see some benefits there, but I still feel like I'm hopeless sometimes.

Aucun commentaire:

Enregistrer un commentaire