简体   繁体   English

如何强制使用的模板参数在C ++中实现某些接口?

[英]How can I enforce that a template parameter used implements some interface in C++?

我不认为这在C ++中是可能的,我有什么选择来模拟行为?

Use std::is_base_of as: 使用std::is_base_of为:

template<typename T>
class A
{
    static_assert(std::is_base_of<IMyInterface, T>::value, 
                  "T must derive from IMyInterface");
};

You can same in function template as well. 您也可以在功能模板中使用相同的功能。

You can use std::is_base_of<YourInterface, YourParameter> , and make an error if the result is false . 您可以使用std::is_base_of<YourInterface, YourParameter> ,如果结果为false ,则会出错。 Remember this is C++11. 记住这是C ++ 11。

Some polymorphic interface or some static interface? 一些多态接口还是一些静态接口? The latter can be checked by Boost Concepts . 后者可以通过Boost Concepts检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C ++:我可以在模板参数包中强制执行至少1个参数 - C++: Can I enforce at least 1 agument in a template parameter pack 在 C++,如何将模板参数强制为范围枚举值类型? - in C++, How to enforce template parameter to be of a scoped enum value type? 如果没有 RTTI,在 C++ 中,我如何在运行时确定集合中的 object 是否实现接口 - Without RTTI, in C++ how can I determine at runtime if an object in a collection implements an interface 可以使用C ++聚合初始化来构造实现接口的类的实例吗? - Can C++ aggregate initialization be used to construct an instance of a class which implements an interface? 如何添加实现c ++接口的标签? - How to add a label that implements a c++ interface? 如何在它实现的接口中告诉C ++ mix - How to tell a C++ mixin the interface it implements 如何访问 C++ 模板参数包中的类型? - How can I access the types in a C++ template parameter pack? 如何在C ++中简化此“变量作为模板参数”? - How can I simplify this “variable as template parameter” in C++? 我如何将Lambda表达式传递给C ++模板作为参数 - How I can pass lambda expression to c++ template as parameter 我应该在运行时还是编译时强制执行C ++接口? - Should I enforce a C++ interface at runtime or compile time?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM