如何指定模板类在c++中实现某些方法
How to specify that a template class implements certain methods in C++?
在Java泛型中,可以简单地使用MyClass<T implements SomeInterface>
。然而,我想不出一个与此等价的c++。
然后,当我有一个模板类T
时,我如何指定这个T
支持哪些特定的方法?
概念是你正在寻找的。但是,它们还没有在当前的c++标准中。所以你能做的就是使用SFINAE
确定某种类型是否尊重某种接口的类型trait可以由寻找某个成员的许多类型trait组成。
类型trait用来确定一个类是否具有如下的特定成员:
template<typename T>
struct has_member1 {
private:
template<typename C> static std::true_type test(decltype(C::THE_MEMBER_NAME)*);
template<typename C> static std::false_type test(...);
public:
constexpr static bool value = decltype(test<T>(nullptr))::value;
};
现在你已经可以检查一个特定的成员了。要检查接口,您可以这样做:
template<typename T>
struct is_my_interface {
constexpr static bool value =
has_member1<T>::value &&
has_member2<T>::value &&
has_member3<T>::value;
};
现在你的模板类:
// declare it
template<typename, typename = void> struct MyClass;
template<typename T>
struct MyClass<T, enable_if_t<is_my_interface<T>>> {
// class body
};
相关文章:
- 实现无开销push_back的最佳方法是什么
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 这是实现图形的坏方法吗
- 在 c++ 中实现嵌套循环的更短方法吗?
- 如何实现 Front() 方法以返回模板化双向链表C++的第一个元素?
- 如何在从抽象基派生的类中实现相同的方法?
- C++数组队列实现方法错误
- 有没有一种通用的方法来实现不变量
- 'using namespace'实现细节的便捷方法(仅标头库)?
- 使用非递归插入方法实现 AVL 树
- C ++类型特征:确保子类实现方法
- 实现基于数字值(正、负、零)的条件表达式的最佳方法
- 在C++上实现高斯赛德尔迭代方法
- C++方法实现:是否可以避免每次都键入类名?
- 如何知道C2259 VS 2017错误未实现哪种方法?
- C++强制在子类中实现方法,但具有不同的签名
- 避免在每个派生类中重新实现方法调用
- C :执行模板类型实现方法
- 在C++中实现方法时继承不起作用
- 还有更好的实现方法吗?