-1

I am pretty new to c++ and I have the following error:

error: explicit specialization of 'get' in class scope
template <> string get<string>() {

This is the code

class ReadFile {
public:
    template <typename T> T get() {
        //...
    }

    template <> string get<string>() {
        //...
    }
private:
    //...
};

By reading the error code, I wrote the template function outside the class scope and I got this error:

duplicate symbol __ZN8ReadFile3getINSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEEET_v in:

So if that is not working how should it be written? Thank you for any help!

When I wrote it ooutside the class scope I wrote it this way:

class ReadFile {};
template <> string ReadFile::get<string>() {
//...
}
yank7
  • 29
  • 4

1 Answers1

3

You need inline

template <> inline string ReadFile::get<string>() {
//...
}

Functions declared within a class definition (e.g. inside class ReadFile { ... };) are inline by default. This is why you only see this problem when you move the function definition outside of the class definition.

Conventionally C++ code can be divided into code in source files and code in header files. Source files are only compiled once but header files may be compiled multiple times, so code in header files potentially causes multiple definition errors. So, generally speaking, this is why header files should only contain declarations and definitions should be placed in source files (there are many exceptions to this principle). But historically there was felt to be a need to put function definitions in header files so that they could be inlined by the compiler, so the inline keyword was invented for that purpose.

However it has never been the meaning of the inline keyword that a function should be inlined, it's only ever been a way to avoid the multiple definition errors that would otherwise result from compiling function definition code more than once.

Further with modern compilers and linkers functions can be inlined wherever they are so placing a function in a header file is now usually just a matter of convenience. The exception to this is function templates and methods of class templates which (for completely different reasons) still need to go in header files and still need to be inlined for this reason.

john
  • 85,011
  • 4
  • 57
  • 81