3

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"
anatolyg
  • 26,506
  • 9
  • 60
  • 134
Superlokkus
  • 4,731
  • 1
  • 25
  • 57

2 Answers2

4

The correct declaration of a template friend class is :

template<class F> friend class library_file;

see Class template with template class friend, what's really going on here?

Community
  • 1
  • 1
Daniel
  • 1,172
  • 14
  • 31
2

You forgot the class keyword in library_file.h, it compiles just fine after that

#ifndef CMAKE_CPP_SPIELWIESE_LIBRARY_H
#define CMAKE_CPP_SPIELWIESE_LIBRARY_H

template <typename F>
class library_file;

class library {
    template <typename F>
    friend class library_file;

};


#endif //CMAKE_CPP_SPIELWIESE_LIBRARY_H
buld0zzr
  • 962
  • 5
  • 10