可以使用CRTP和以接口为参数的函数吗
Can you use CRTP and functions taking an interface as a parameter?
在C++中,纯虚拟类通常用于运行时多态性。
所以你有:
class IInterfaceA
{
virtual void DoFoo() = 0;
};
以及派生类,如:
class CFancyObject : public IInterfaceA
{
...
然后可以用于以下功能:
void Foo(IInterfaceA &interface);
但这是运行时的情况,如果对象在编译时是已知的,我们可以使用CRTP:做得更好
template<class T> class IInterfaceA
{
public:
void DoFoo()
{
static_cast<T*>(this)->CallDerivedFunction();
}
}
class CFancyObject : public IInterfaceA<CFancyObject>
{
...
}
在以IInterface为参数的函数中,是否可以使用基于CRTP的派生类?
void Foo(IInterfaceA<?> &interface);
接口用于将类的API与其实现解耦。通过引入模板参数,您将实现与接口紧密耦合,从而破坏了整个目的。CRTP旨在解决一系列不同的问题。
如果将接口模板化,那么将其作为参数的函数也必须模板化。一旦完成了这一点,使用接口类和使用实现类就没有区别了。
template<class T>
void Foo(IInterfaceA<T> &interface) { interface.DoFoo(); }
与相同,没有任何优势
template<class T>
void Foo(T &object) { object.DoFoo(); }
你就不能这么做吗:
template<class T> class IInterfaceA
{
public:
template<class T2>
void DoFoo(IInterfaceA<T2> &interface)
{
static_cast<T*>(this)->CallDerivedFunction(interface);
}
}
class CFancyObject : public IInterfaceA<CFancyObject>
{
template<class T2>
CallDerivedFunction(IInterfaceA<T2> &interface) {...}
}
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类