在 Java 中,您可以定义泛型类,该类只接受扩展您选择的类的类型,例如:
public class ObservableList{...} 这是使用extends"关键字完成的.
C++ 中是否有一些简单的等价于 this 关键字?
我建议使用 Boost 的 静态断言 功能与 is_base_of 来自 Boost Type Traits 库:
template类 ObservableList {BOOST_STATIC_ASSERT((is_base_of::value));//是的,需要双括号,否则逗号将被视为宏参数分隔符...};
在其他一些更简单的情况下,您可以简单地向前声明一个全局模板,但只为有效类型定义(显式或部分专门化)它:
template类 my_template;//声明,但不定义//int 是一个有效的类型模板<>class my_template{...};//所有指针类型都有效模板class my_template{...};//所有其他类型都无效,并且会导致链接器错误消息. [次要编辑 6/12/2013:使用声明但未定义的模板将导致链接器,而不是编译器错误消息.]>
In Java you can define generic class that accept only types that extends class of your choice, eg:
public class ObservableList<T extends List> {
...
}
This is done using "extends" keyword.
Is there some simple equivalent to this keyword in C++?
I suggest using Boost's static assert feature in concert with is_base_of from the Boost Type Traits library:
template<typename T>
class ObservableList {
BOOST_STATIC_ASSERT((is_base_of<List, T>::value)); //Yes, the double parentheses are needed, otherwise the comma will be seen as macro argument separator
...
};
In some other, simpler cases, you can simply forward-declare a global template, but only define (explicitly or partially specialise) it for the valid types:
template<typename T> class my_template; // Declare, but don't define
// int is a valid type
template<> class my_template<int> {
...
};
// All pointer types are valid
template<typename T> class my_template<T*> {
...
};
// All other types are invalid, and will cause linker error messages.
[Minor EDIT 6/12/2013: Using a declared-but-not-defined template will result in linker, not compiler, error messages.]
这篇关于仅接受某些类型的 C++ 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
std::reference_wrapper 和简单指针的区别?Difference between std::reference_wrapper and simple pointer?(std::reference_wrapper 和简单指针的区别?)
常量之间的区别.指针和引用?Difference between const. pointer and reference?(常量之间的区别.指针和引用?)
c++ - 如何从指向向量的指针访问向量的内容?How to access the contents of a vector from a pointer to the vector in C++?(c++ - 如何从指向向量的指针访问向量的内容?)
*& 的含义和**&在 C++ 中Meaning of *amp; and **amp; in C++(*amp; 的含义和**amp;在 C++ 中)
为什么我不能对普通变量进行多态?Why can#39;t I do polymorphism with normal variables?(为什么我不能对普通变量进行多态?)
取消引用已删除的指针总是会导致访问冲突?Dereferencing deleted pointers always result in an Access Violation?(取消引用已删除的指针总是会导致访问冲突?)