非模板类中的模板化朋友类,其中朋友也使用该类

时间:2016-06-27 10:06:08

标签: c++ oop templates c++11 c++14

背景

我有一个非模板化的类,名为library和模板化的类library_file,其目的是为不同的文件类型设置模板参数F(例如std::fstreamQFile等等)保存/加载library

假设

所以我在library_file的定义和最后一个朋友声明之前提出了library的前瞻声明。因为,library_file包括library,否则我会在依赖圈中。

问题

朋友声明以

失败
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.

代码

/*! @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"

2 个答案:

答案 0 :(得分:4)

模板友好类的正确声明是:

configureScene={() => ({
  ...Navigator.SceneConfigs.FloatFromBottom,
  gestures: {}, // or null
})

请参阅Class template with template class friend, what's really going on here?

答案 1 :(得分:2)

您忘记了class中的library_file.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 class library_file;

};


#endif //CMAKE_CPP_SPIELWIESE_LIBRARY_H