variadic template und const static class member



  • Hallo!

    Ich experimentiere gerade mit variadic templates:

    #include <iostream>
    
    template <int x, int ... y> class multiply
    {
    public:
      static const int value = (sizeof...(y) == 0) ? x : (x * multiply<y, ...>::value);
    };
    
    int main()
    {
      std::cout << multiply<3, 4>::value << std::endl;
      return 0;
    }
    

    Allerdings bekomme ich beim Compilieren den Fehler:

    /tmp/ccaItgJt.o: In function `main':
    test.cpp:(.text+0x44): undefined reference to `multiply<3, 4>::value'
    collect2: ld returned 1 exit status
    

    Mit normalen templates bekomme ich den Fehler nicht:

    #include <iostream>
    
    template <int x, int y> class multiply
    {
    public:
      static const int value = x * y;
    };
    
    int main()
    {
      std::cout << multiply<3, 4>::value << std::endl;
      return 0;
    }
    

    Woran könnte das liegen?

    Danke im Voraus.



  • Welcher Compiler kann das denn schon?, bzw. welchen benutzt du?



  • Ich habe gcc 4.3.3 und kompiliere mit g++ --std=c++0x test.cpp .



  • Es kompiliert jetzt:

    #include <iostream>
    
    template <int ... x> struct multiply;
    
    template <> struct multiply<>
    {
      static const int value = 1;
    };
    
    template <int x, int ... y> struct multiply<x, y...>
    {
      static const int value = x * multiply<y, ...>::value;
    };
    
    template <int x, int ... y> const int multiply<x, y...>::value;
    
    int main()
    {
      std::cout << multiply<3, 4>::value << std::endl;
      return 0;
    }
    

    Allerdings ist das Ergebnis immer Null. 😕



  • Ah, jetzt hab' ich's: Es muss multiply<y ...>::value; und nicht multiply<y, ...>::value; heißen. 🙂


Anmelden zum Antworten