default-template-argument bei funktionen



  • hi
    default-template-argumente bei funktionen sind ja verboten. kann man das mit klassen irgendwie wrappen, so dass man das defaulting hat aber die klasse immer noch wie eine funktion aussieht?

    mfg


  • Mod

    #include<iostream>
    
    using namespace std;
    
    template<int I> void foo_function()
    {
      cout << I << endl;
    }
    
    template<int I=5> struct foo_wrapper
    {
      foo_wrapper() {foo_function<I>();}
    };
    
    int main()
    {
      foo_wrapper<>();
    }
    

    Mit Rückgabewerten wird es jedoch schwieriger. Vielleicht so?

    #include<iostream>
    
    using namespace std;
    
    template<int I> double foo_function()
    {
      cout << I << endl;
      return I*2;
    }
    
    template<int I=5> struct foo_wrapper
    {
    private:
      double temp;
    public:
      foo_wrapper() : temp(foo_function<I>()) {}
      operator double() {return temp;}
    };
    
    int main()
    {
      cout << foo_wrapper<>() << endl;
    }
    

    Was besseres fällt mir gerade nicht ein.



  • zu kompliziert gedacht 😉

    Uerbladung ist die Loesung

    template<int I>
    int foo() { return I; }
    
    int foo() {
      return foo<5>();
    }
    

Anmelden zum Antworten