我不确定如何解释它,因为我真的不知道正确的术语,但这里有一个例子:
template <typename T>
struct PointerWrapper {
T *ptr;
};
struct Base {};
struct Derived : public Base {};
void test(PointerWrapper<Base>) {}
int main() {
PointerWrapper<Derived> p;
test(p);
return 0;
}
由于“Derived”是从“Base”派生的,而“PointerWrapper”结构仅适用于指向模板指定类型的指针,因此这没有任何问题。但是编译器提示:
asdfg.cpp:15:11: error: could not convert ‘p’ from ‘PointerWrapper<Derived>’ to ‘PointerWrapper<Base>’
我什至试过test(reinterpret_cast<PointerWrapper<Base>>(p))
,但它说:
asdfg.cpp:15:51: error: invalid cast from type ‘PointerWrapper<Derived>’ to type ‘PointerWrapper<Base>’
那我该怎么办呢?
最佳答案
PointerWrapper<Base>
和 PointerWrapper<Derived>
是完全不同的类型,尽管 Base
之间存在关系和 Derived
.
如果你想允许任何PointerWrapper<>
要传入,请执行以下操作:
template<typename T>
void test(PointerWrapper<T>)
{ }
如果你只想允许 PointerWrapper<T>
T
的实例源自 Base
, 做:
template<typename T>
void test(
PointerWrapper<T>,
typename std::enable_if<std::is_base_of<Base, T>::value, void*>::type = 0
)
{ }
如果您使用的是 C++03,请替换 std::
与 boost::
并摆脱 ::value
.
关于c++ - 如何将模板实例传递给需要将模板参数传递给基类的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9740888/