如何指定模板类在c++中实现某些方法

How to specify that a template class implements certain methods in C++?

本文关键字:实现 方法 c++ 何指定      更新时间:2023-10-16

在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
};