只接受某些类型的C ++模板 [英] C++ templates that accept only certain types
问题描述
在Java中,您可以定义只接受扩展所选类型的类的泛型类,例如:
In Java you can define generic class that accept only types that extends class of your choice, eg:
public class ObservableList<T extends List> {
...
}
。
在C ++中有一个简单的等价于这个关键字吗?
Is there some simple equivalent to this keyword in C++?
推荐答案
我建议使用Boost的 static assert 功能与 is_base_of
:
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 an declared- but-not-defined模板将导致 链接器,而不是编译器,错误消息。]
[Minor EDIT 6/12/2013: Using a declared-but-not-defined template will result in linker, not compiler, error messages.]
这篇关于只接受某些类型的C ++模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!