C++模板:访问模板变量
C++ templates: Accessing template variables
我是C++世界的新手。
我正在尝试使用模板来实现代码。
template<class PageType>
class Book
{
//implementation
public:
PageType* FreeQ; //holds the pointers to pages which are yet to be written
PageType* BusyQ; //holds the pointers to pages which are being written
PageType* DoneQ; //holds the pointers to pages which were written
getPagetoWrite(); //Get from FreeQ and put in BusyQ
setPageAsFree(); //Erase data and put in FreeQ
}
//example for PageType implementation
class PlasticType
{
mutex; // must
status; // must
*prev; // must
*next; // must
Write( );
Read();
}
我想知道是否有任何方法可以通知编译器PageType
的实现必须包含将在类Book
实现(在getPagetoWrite
和setPageAsFree
中)中使用的特定变量,而不创建类型PageType
的实例。
希望我说清楚了。
我不认为强制PageType
包含特定变量是可能的,这在模板实例化期间的编译时很简单,您真的不需要其他任何东西。您可以使用C++11 std::is_base_of
来使用static_assert
强制您的PageType
实现一些基类,您可以将getPagetoWrite和setPageAsFree放入其中,但仍然必须实例化您的模板-这是可以的。
#include <type_traits>
class Base {
};
class X : public Base {
};
class Z {
};
template <typename T>
class Foo {
static_assert(std::is_base_of<Base,T>::value,"must be derived from Base");
public:
Foo() {
}
};
int main(int argc, char** argv) {
Foo<Z> foo_z_type; // gives compile error: static assertion failed: must be derived from Base
Foo<X> foo_z_type; // OK
return 0;
}
http://coliru.stacked-crooked.com/a/bf91079681af3b0e
据我所知,您可以只使用代码中应该存在的变量或函数的名称。像这样:
void getPagetoWrite()
{
...
//PageType should have a member called pagenum for which operator++ makes sense
BusyQ->pagenum++;
...
}
如果用某个没有pagenum
成员的类实例化Book模板,则会出现编译时错误。
相关文章:
- 从不同C++类的成员变量访问成员函数
- 在主函数中C++私有变量访问
- 互锁变量访问(在布尔值上)和 std::atomic_flag 之间的区别
- C++中的变量访问内联函数
- 无法使用子类变量访问超类公共成员
- 优化成员变量访问
- Ifstream:打开可使用变量访问的文件
- 使用'this->'成员变量访问的性能
- 从成员变量访问静态 constexpr 成员,GCC 错误?
- TLS变量访问的结果未缓存
- 通过const成员变量访问内联函数
- 获取通过环境变量访问的文件的位置
- 静态变量访问
- 从函数变量访问结构变量的成员
- 从另一个变量访问变量
- 使用变量访问结构中的任何数据
- 如何使用另一个变量访问对象的变量/方法
- 使用用户变量访问结构的成员?C++
- 我需要通过基类静态变量访问派生类成员
- 如何将一个文件中存在的全局常量变量访问到另一个文件