我想通过一个派生类作为一个std :: shared_pointer到一个函数,其参数是基类,它有一个模板。C++ std :: shared_pointer与模板基类
下面是一个完整的例子:
template <class T>
class Base {
public:
std::string typeName()
{
int status;
char *realName = abi::__cxa_demangle(typeid(T).name(), 0, 0, &status);
std::string ret(realName);
free(realName);
return ret;
}
};
class Derived : public Base<float> {};
我想调用的功能是“doSomething的”与共享指针。
template <class V>
void doSomethingNotShared(Base<V> *test)
{
std::cout << "Not shared type: " << test->typeName() << std::endl;
};
template <class V>
void doSomething(std::shared_ptr<Base<V>> test)
{
std::cout << "Shared type: " << test->typeName() << std::endl;
};
这里是显示我想如何使用它并指出编译错误的主要功能。
int main()
{
std::shared_ptr<Derived> testval1 = std::shared_ptr<Derived> (new Derived());
doSomething(testval1); // <- Compilation error
Derived *testval2 = new Derived();
doSomethingNotShared(testval2);
std::shared_ptr<Base<float>> testCast = std::dynamic_pointer_cast<Base<float>>(testval1); // Would rather not have to do this if there is another way ...
doSomething(testCast); // <- No error runs fine
}
有没有什么办法让与doSomething(testval1);
这项工作?我希望不必使用dynamic_pointer_cast
(或任何其他类型的投射机制),只需使用Derived。
主要错误是:std::shared_ptr<Derived> is not derived from std::shared_ptr<Base<V> >
我可以创建一个“AnyBase”类删除模板参数,但随后会删除某些类型安全的,我在我的实际应用,这是必须到位必须的。
有一件事我考虑是创建新类AnyBase
和std::shared_ptr<AnyBase>
之间的映射,然后使用功能doSomethingNotShared
处理的类型安全,并使用查找映射得到的shared_ptr。 (见下文)
std::map<AnyBase *, std::shared_ptr<AnyBase>>
编辑:
实例从我的应用程序确认的类型安全:
template <class V, class W, class X>
void addRuleEdge(Bookkeeper<V> *bookkeeper, std::shared_ptr<IRule<V, W>> rule, ITask<W, X> *consumer)
在这种情况下,我想在第一个匹配Bookkeeper
之间的类型V
模板类型IRule
以及IRule
(W
)的第二个模板参数的匹配类型与第一个模板类型ITask
的匹配类型。这用作用户的API调用,以确保在添加边时,类型在编译时正确排列。
由于您正在铸造'static_pointer_cast',因此适用。 – NathanOliver
理想情况下,我想打电话给doSomething(testval1); ...所以没有铸造任何东西。动态强制转换是为了显示一种方法能够将doSomething函数与模板化的shared_ptr一起使用。 – Jameshobbs
我知道。只要让你知道动态演员阵容是不需要的时候。看起来他们只有一个转换构造函数,如果该对象是临时的。他们不会自动转换左值。 – NathanOliver