【发布时间】:2015-06-08 11:27:44
【问题描述】:
我有一个 C++ 库,它是 C 库的包装器。工厂类Creator 创建对象,每个对象代表C 库的部分功能。
这些类构造函数是私有的,以确保所有对象都是通过 Creator 类创建的,因为 C 库需要一些内部魔法(我在下面的简化示例中省略了)。
一切正常,但我有以下“问题”:
在UsesAandB类中,我必须指定A<>的模板参数两次:
一次在成员声明中(std::shared_ptr<A<int>>),一次在构造函数的初始化列表中(creator->createA<int>)。
既然我已经知道成员 aInt 将是 std::shared_ptr<A<int>> 类型,我如何使用这些知识在构造函数中调用相应的 createA<int>() 方法而不重复 int 或者我如何避免调用createA<int>() 呢?
#include <memory>
class Creator;
template<typename T>
class A
{
friend class Creator;
private:
A(int param) {}
T value;
};
class B
{
friend class Creator;
private:
B(){}
};
class Creator
{
public:
template<typename T>
std::shared_ptr<A<T>> createA(int param) { return std::shared_ptr<A<T>>(new A<T>(param)); }
std::shared_ptr<B> createB() { return std::shared_ptr<B>(new B());}
};
class UsesAandB
{
public:
UsesAandB(std::shared_ptr<Creator> creator)
: creator(creator),
aInt(creator->createA<int>(0)),
aDouble(creator->createA<double>(1)),
b(creator->createB())
{
}
private:
std::shared_ptr<Creator> creator;
std::shared_ptr<A<int>> aInt;
std::shared_ptr<A<double>> aDouble;
std::shared_ptr<B> b;
};
int main()
{
auto creator = std::make_shared<Creator>();
UsesAandB u(creator);
return 0;
}
【问题讨论】:
-
类 A 可以有一个 typedef (例如 A::type) 用于实例化它的类型。然后,您可以使用该 typedef。编辑:我不确定是否有可能摆脱未初始化的共享指针。 :)
-
@rozina: 并像这样使用它?
aInt(creator->createA<A::type>(0))?好的,可以,但是Creator可以使用typedef以某种方式推断它吗? -
不是这样,因为 A 是一个模板,所以 A::type 不起作用。 A
::type 会,但这没有任何效果:) 我会用我的想法写一个答案。虽然我怀疑你会满意:D