So I followed this SO answer for my purposes, and I really do not know how to resolve this error. When I try to access audioType[wav]
or audioType[mp3]
, the error below comes up. Looking up the internet was not helpful for me.
error: no viable overloaded operator[] for type 'const std::map<AudioTypes, const char *>
note: candidate function not viable: 'this' argument has type 'const
std::map<AudioTypes, const char *>', but method is not marked const
mapped_type& operator[](const key_type& __k);
// WAVFile.h
class WAVFile {
// ...
private:
enum AudioTypes: int;
static std::map<AudioTypes, const char*> audioType;
// ...
}
// WAVFile.cpp
enum AudioTypes: int {
wav,
mp3
};
static map<AudioTypes, const char*> audioType = {
{wav, "wav"},
{mp3, "mp3"}
};
bool WAVFile::exportAudio(const char* filename, const char* filetype) {
// temporary test code
cout << audioType[wav] << endl;
return true;
}
// main.cpp
int main() {
file.exportAudio("export_i ran.wav","wav") ? cout << "Exported\n" : cout << "Failed\n";
return 0;
}
As already pointed out, the reason for that error is - as the error message explains - that operator[]
of std::map
is not a const
qualified member function. (I'm a bit surprised by this, I thought there was a const
overload)
A possible fix is to use the member function at
, which has this const qualified overload, and should thus be working with const
qualified std::map
s.
Also note that in the code you showed there's a possible issue:
class WAVFile {
static std::map<AudioTypes, const char*> audioType;
}
and
static map<AudioTypes, const char*> audioType = {
{wav, "wav"},
{mp3, "mp3"}
};
are not the same variable. You should add the class scope before the definition and get rid of the static
:
map<AudioTypes, const char*> WAVFile::audioType = {
{wav, "wav"},
{mp3, "mp3"}
};
Moreover, you should either move the definition of enum AudioTypes
to the header, or possible provide a forward declaration.
After fixing a few issues, in particular the missing WAVFile::
before audioType
and AudioTypes
and the static before the definition of audioType
, this code builds:
#include <map>
#include <iostream>
using namespace std;
class WAVFile {
public:
bool exportAudio(const char* filename, const char* filetype);
private:
enum AudioTypes: int;
static std::map<AudioTypes, const char*> audioType;
};
enum WAVFile::AudioTypes: int {
wav,
mp3
};
map<WAVFile::AudioTypes, const char*> WAVFile::audioType = {
{wav, "wav"},
{mp3, "mp3"}
};
bool WAVFile::exportAudio(const char* filename, const char* filetype) {
cout << audioType[wav] << endl;
return true;
}
int main() {
WAVFile file;
file.exportAudio("export_i ran.wav","wav") ? cout << "Exported\n" : cout << "Failed\n";
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With