从构造函数中的成员变量中减去模板参数 [英] Deduce template parameter from member variable in constructor

查看:117
本文介绍了从构造函数中的成员变量中减去模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++库,它是C库的包装器。工厂类 Creator 创建对象,每个对象表示C库功能的一部分。
这些类构造函数是私有的,以确保所有对象都通过 Creator 类创建,因为C库需要一些内部魔术(在下面我省略,简化示例)。

I have a C++ library which is a wrapper for a C library. A factory class Creator creates objects of which each represents parts of the functionality of the C library. These class constructors are private to ensure that all objects are created through that Creator class because the C library requires some internal magic (which I omitted in the following, simplified example).

一切正常,但我有以下问题:

It all works, but I have the following "problem":

c $ c> UsesAandB 我必须指定 A<> 两次的模板参数:
一旦在成员声明code> std :: shared_ptr< A< int>> )并且一次在构造函数的初始化列表中( creator-> createA< int> code>)。

In class UsesAandB I have to specify the template parameter of A<> twice: Once in the member declaration (std::shared_ptr<A<int>>) and once in the initialization list of the constructor (creator->createA<int>).

由于我已经知道成员 aInt 将是 std :: shared_ptr< A< int>> ,我如何使用这些知识来调用相应的 createA< int>方法在构造函数中不重复 int 或者如何避免调用 createA ()

Since I already know that member aInt will be of type std::shared_ptr<A<int>>, how can I use this knowledge to call the corresponding createA<int>() method in the constructor without repeating int or how can I avoid the call to createA<int>() at all?

#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;
}


推荐答案

shared_ptr ,您需要将其传递给模板函数,如下所示:

To get the type from the shared_ptr, you need to pass it to a template function like this one:

template <typename U>
shared_ptr< A<U> > CreateA( std::shared_ptr<Creator>& c,
                            const shared_ptr< A<U> >& p,
                            const U& val )
{
    return c->createA<U>(val);
}

然后只需:

aInt(CreateA(creator, aInt, 0 )),

此处的示例 - http://ideone.com/Np7f8t

这篇关于从构造函数中的成员变量中减去模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆