java - 在 C++ 中使用模板检查继承

标签 java c++ templates

我有一个类,它是另一个实现所需功能的类的包装类(用作公共(public)接口(interface))。所以我的代码看起来像这样。

template<typename ImplemenationClass> class WrapperClass {
// the code goes here
}

现在,我如何确保 ImplementationClass 可以仅从一组类派生,类似于 java 的泛型

<? extends BaseClass>

语法?

最佳答案

它很冗长,但你可以这样做:

#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_base_of.hpp>

struct base {};

template <typename ImplementationClass, class Enable = void>
class WrapperClass;

template <typename ImplementationClass>
class WrapperClass<ImplementationClass,
      typename boost::enable_if<
        boost::is_base_of<base,ImplementationClass> >::type>
{};

struct derived : base {};
struct not_derived {};

int main() {
    WrapperClass<derived> x;

    // Compile error here:
    WrapperClass<not_derived> y;
}

这需要一个对标准有良好支持的编译器(最新的编译器应该没问题,但旧版本的 Visual C++ 就不行)。有关详细信息,请参阅 Boost.Enable_If documentation .

正如 Ferruccio 所说,一个更简单但功能更弱的实现:

#include <boost/static_assert.hpp>
#include <boost/type_traits/is_base_of.hpp>

struct base {};

template <typename ImplementationClass>
class WrapperClass
{
    BOOST_STATIC_ASSERT((
        boost::is_base_of<base, ImplementationClass>::value));
};

关于java - 在 C++ 中使用模板检查继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55440/

相关文章:

java - 无法使用 IAM 用户的访问 key 代入第三方 AWS 账户的角色

java - 将 UUID 存储为 base64 字符串

c++ - 逆时针定向多边形线所需的编码算法

c++ - 为什么 std::unique_ptr 构造函数接受外部指针?

C++ 重载函数作为模板参数

c++ - 专门的模板类循环依赖

java - 继承期间TestNG中@BeforeClass方法执行

java - Linux/weblogic Excel 下载给出损坏的字符

c++ - 竞争条件效应

c++ 11模板类型别名以减轻痛苦