<分区>
有没有可能实现这样的目标?与其使用不同的函数来实例化不同的类,不如编写一个函数来实例化不同的类,如果它们从基类派生并采用相同的参数,那就太好了。
#include <iostream>
#include <string>
#include <vector>
#include <limits>
class Base
{
void DoSomething()
{
std::cout << "Oh yes" << std::endl;
}
};
class Derived1 : public Base
{
};
class Derived2 : public Base
{
};
template <typename T>
T* Create<T>()
{
return new T;
}
int main()
{
auto* test = Create<Derived1>();
test->DoSomething();
delete test;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
return 0;
}
你的
void DoSomething()
类成员函数是private
默认情况下,如 vsoftco's comment 所述.制作 public
可能会解决您的主要(语法)问题。
从语义上看:
不要使用 new
/new[]
, delete
/delete[]
请直接使用原始指针/c 风格的数组!除非你真的知道你需要它,并且你想要低级控制,否则它会使你的代码不必要地复杂化。
对于这样的Factory pattern ,我建议使用来自 c++ 标准动态内存管理工具的智能指针:
template <typename T>
std::unique_ptr<T> Create() {
return std::unique_ptr<T>(new T());
// Alternatively for c++14
// return std::make_unique<T>();
}
上面是most simple variant ,其中工厂方法只是将所有权交给调用者。
一个真正的工厂可能会负责将更多的观察者或其他东西与创建的实例连接起来,你最终会需要一些 std::shared_ptr<T>
/ std::weak_ptr<T>
成语代替。
仔细查看您的代码,如下所示:
template <typename T>
T* Create() {
return new T;
}
int foo() {
auto* test = Create<Derived1>();
test->DoSomething();
delete test; // what actually happens if Create<Derived1>() or
// test->DoSomething(); throws an exception?
// Is the allocated memory tidied up?
// Irrelevant:
// std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
return 0;
}
int main() {
int retcode = foo(); // Slightly deviated your sample
// do something else ...
return retcode;
}