Template Spezialisierung mit Werte-Mapping



  • Sorry, für den doofen Titel, mir ist nichts besseres eingefallen. 😉

    Hallo,

    ich habe eine Funktion

    template<class T>
    void send(T item);
    

    Nun will ich innerhalb von send den Typ T auf einen Wert mappen (bspws. T = int => MPI_INT). Existiert kein Mapping, so soll send nicht spezialisiert werden.

    Ich habe das folgendermaßen hinbekommen. id ist hier der MPI_INT (welches kein Typ, sondern ein Wert ist):

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    template<class T>
    struct MpiType {
      static const bool has_type = false;
    };
    
    template<>
    struct MpiType<int> {
      static const bool has_type = true;
      static const int id = 1;
    };
    
    template<>
    struct MpiType<double> {
      static const bool has_type = true;
      static const int id = 2;
    };
    
    template<>
    struct MpiType<const char*> {
      static const bool has_type = true;
      static const int id = 3;
    };
    
    
    template<class T,
             typename = std::enable_if<MpiType<T>::has_type, T>>
    void send(T item)
    {
      std::cout << "Send with " << MpiType<T>::MPI_Datatype << std::endl;
    }
    
      
    int main() {
        int i = 4;
        send(i);
        send(4);
        double d = 5;
        send(d);
        send("foo");
        return 0;
    }
    
    

    Es scheint soweit zu funktionieren. Meine Fragen:

    • Seht ihr irgendwelche potentiellen Probleme?
    • Gibt es eine bessere / schönere / idiomatischere Lösung?

    C++ 11

    Danke!


  • Mod

    Vielleicht könnten wir dir allgemeinere Ratschläge geben, wenn du den Rahmen deines Problems erläuterst.


Anmelden zum Antworten