Błąd przy wywołaniu funkcji z klasy przekazywanej jako template

0

Witam!

Mam taki kod:

#include <iostream>
#include <ostream>

template<size_t N>
struct string_literal
{
  constexpr string_literal(const char(&str)[N]) {
    std::copy_n(str, N, value);
  }
  
  void show() {
    std::cout << "AAA" << std::endl;
  }

  char value[N];
};

template <string_literal x>
struct foo 
{
    void fun() {
      x.show();
      std::cout << x.value << std::endl;
    }
};

int main() {
 foo<"2323"> f;
 f.fun();
 return 0;
}

Dlaczego przy kompilacji dostaje taki błąd :

g++ -std=c++2a -o main main.cpp
main.cpp: In instantiation of ‘void foo<x>::fun() [with string_literal<...auto...> x = string_literal<5>{"2323"}]’:
main.cpp:29:7:   required from here
main.cpp:22:13: error: passing ‘const string_literal<5>’ as ‘this’ argument discards qualifiers [-fpermissive]
   22 |       x.show();
      |       ~~~~~~^~
main.cpp:11:8: note:   in call to ‘void string_literal<N>::show() [with long unsigned int N = 5]’
   11 |   void show() {
      |        ^
make: *** [Makefile:9: main] Error 1

Czy chodzi o to ,że do obiektu x nie można się odwołać przez this ? Nie rozmumiem też ,że jak dodam flagę -fpermissive to kod mi się skompiluje (oczywiście z warningiem) ?

Pozdrawiam

2

void show() wg deklaracji funkcji przyjmuje ona non-const this, a parametr szablonu jest const. Rozwiązanie:

  void show() const {
    std::cout << "AAA" << std::endl;
  }

1 użytkowników online, w tym zalogowanych: 0, gości: 1