lundi 27 juin 2016

Templated friend class in nontemplate class, where friend also uses the class

Background

I have a non templated class, called library and a templated class library_file which is intended to have a template parameter F for different file types (like std::fstream or QFile and so on) to save/load a library on.

Assumption

So I put a forward declaration of library_file before my definition of library and a friend declaration in the last one. Because, since library_file includes library I would otherwise be in a dependency circle.

Problem

The friend declaration fails with

In file included from /Users/markus/Entwicklung/cmake_Spielwiese/library.cpp:4: /Users/markus/Entwicklung/cmake_Spielwiese/library.h:12:12: error: C++ requires a type specifier for all declarations friend library_file; ~~~~~~ ^ /Users/markus/Entwicklung/cmake_Spielwiese/library.h:12:12: error: friends can only be classes or functions 2 errors generated.


Code

/*! @file library.h
 * */

#ifndef CMAKE_CPP_SPIELWIESE_LIBRARY_H
#define CMAKE_CPP_SPIELWIESE_LIBRARY_H

template <typename F>
class library_file;

class library {
    template <typename F>
    friend library_file;

};


#endif //CMAKE_CPP_SPIELWIESE_LIBRARY_H

/*! @file library_file.h
 * */

#ifndef CMAKE_CPP_SPIELWIESE_LIBRARY_FILE_H
#define CMAKE_CPP_SPIELWIESE_LIBRARY_FILE_H

#include "library.h"

template <typename F>
class library_file {
    F file;
    library l;
};


#endif //CMAKE_CPP_SPIELWIESE_LIBRARY_FILE_H

/*! @file main.cpp
 * */
#include <fstream>
#include "library.h"
#include "library_file.h"

int main() {
    library_file<std::fstream> f;
    return 0;
}
/*! @file library.cpp
 * */

#include "library.h"

Aucun commentaire:

Enregistrer un commentaire