如何将参数传递给Policy的构造函数?

时间:2010-10-31 19:47:38

标签: c++ templates

在代码中:

template<class T>
struct FactorPolicy
{
    T factor_;
    FactorPolicy(T value):factor_(value)
    {
    }
};

template<class T, template<class> class Policy = FactorPolicy>
struct Map
{
};

int _tmain(int argc, _TCHAR* argv[])
{
        Map<int,FactorPolicy> m;//in here I would like to pass a double value to a  
 //FactorPolicy but I do not know how.  
        return 0;
    }

已编辑 [对于Mark H]

template<class T, template<class> class Policy = FactorPolicy>
struct Map : Policy<double>
{
    Map(double value):Policy<double>(value)
    {
    }
};

2 个答案:

答案 0 :(得分:0)

一种方法是提供成员函数模板,该模板将模板arg用于策略。例如:

template<class T, template<class> class Policy = FactorPolicy> 
struct Map 
{
  template <typename V>
  void foo(const Policy<V> &p)
  {
  }
}; 

然后,在主要:

Map<int,FactorPolicy> m;

m.foo(FactorPolicy<double>(5.0));

另一种可能性是通过向Map添加第三个模板arg将其指定为Map模板实例化的一部分:

template<class T, template<class> class Policy = FactorPolicy, 
         class V = double> 
struct Map 
{
  void foo(const V &value)
  {
    Policy<V> policy(value);
  }
}; 

然后:

Map<int,FactorPolicy,double> m;

m.foo(5.0);

答案 1 :(得分:0)

如果要传递double,则需要在Map内部使用FactorPolicy的类型参数加倍,除非您使FactorPolicy构造函数接受double。我不认为这是你想要的。您必须通知Map,Policy需要一个double,因此首先添加该类型参数。其次,我认为你需要从Map构造函数转发实际的double值。

template<class T, typename U, template<class> class Policy = FactorPolicy >
struct Map {
    Map(U val) {
        policy_ = new Policy<U>(val);
    }

    Policy<U>* policy_;
};

int main()
{
    Map<int, double, FactorPolicy> m(5.63);
    return 0;
}