C ++:指定模板参数的基类 [英] C++: specifying a base class for a template parameter

查看:132
本文介绍了C ++:指定模板参数的基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要设计一个框架,并行计算分治算法的结果。
为了使用框架,用户需要指定实现分割阶段(从T到T的函数),征服阶段(从D到D的函数)和T和D本身。

I need to design a framework that computes the result of a divide-et-conquer algorithm in parallel. In order to use the framework, the user needs to specify somehow the procedure that implements the "divide" phase (a function from T to T), the "conquer" phase (a function from D to D) and T and D themselves.

我认为定义两个抽象类, BaseDivide BaseConquer ,它用正确的类型声明一个纯虚方法 compute :这样我有一个类型,概念(从框架的角度),通过派生抽象类包含用户可定义的函数。

I've thought it would be nice to define two abstract classes, BaseDivide and BaseConquer, which declares a pure virtual method compute with the right types: that way I have a type which implements a well-defined concept (from the point of view of the framework) with the user-definable function included by means of derivation of the abstract classes.

我曾经想过使用模板传递类型到框架,所以用户不必实例化它们为了使用框架,所以像这样:

I've thought to use templates to pass the types to the framework, so the user doesn't have to instantiate them in order to use the framework, so something like that:

template <typename T, typename D, typename Divide, typename Conquer> 
D compute(T arg);

我的问题是我想要Divide and Conquer是 BaseDivide BaseConquer :有一种方法在编译时强制执行它?

My problem is that I want that Divide and Conquer to be derived types of BaseDivide and BaseConquer: there is a way to enforce it at compile time? Also: do you think I can achieve a similar result with a cleaner design?

推荐答案

您可以创建如下的基类:

You could create the base classes like this:

struct BaseDivide {
    enum EnumDiv { derivedFromBaseDivide = true };
}

template <typename T, typename D, typename Divide, typename Conquer> 
    static_assert(D::derivedFromBaseDivide);
    D compute(T arg);

额外的Divide and Conquer模板参数的用途是什么?您确定需要他们吗?

What is the purpose of the additional Divide and Conquer template parameters? Are you sure you need them?

这篇关于C ++:指定模板参数的基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆