2010-10-31 171 views
1

在代码:如何将参数传递给策略的构造函数?

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

编辑 [马克H]

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

为什么你想要它? – 2010-10-31 19:56:20

+0

@Alexey如果你看看FactorPolicy的ctor,有一个arg被传递,我希望能够在声明变量Map时传递这个值。像这样:Map 2010-10-31 20:02:12

回答

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)); 

另一种可能性是将其指定为地图模板实例的一部分,通过加入第三模板ARG到地图:

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

Then:

Map<int,FactorPolicy,double> m; 

m.foo(5.0); 
+0

@Michael no我没有,它是一个模板模板类 – 2010-10-31 19:51:57

+0

好吧,我为你指定的_tmain函数工作了吗?因为底线是你无法定义一个变量而不指定所有的(实际)模板参数。 – 2010-10-31 19:52:49

+0

@Michael你的更新,我不是100%肯定,但如果我宣布模板模板,我不必提供模板decl参数。但正如我所说,我不是百分之百确定。 – 2010-10-31 19:54:17

0

如果您要传递double,则需要在Map内部FactorPolicy的类型参数为double,除非您使FactorPolicy构造函数接受double。我不认为这是你想要的。你必须通知Map策略需要一个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; 
} 
+0

@Mark如果我想将因子值传递给ctor,我会做得更简单 - 您不必指定U型。 – 2010-10-31 20:44:15

+0

对于你所声称的,你需要将它定义为'template >'。否则Map如何知道FactorPolicy需要双重?它不能简单地从参数的类型中推断出来,你必须在某个地方明确地说明类型。 – 2010-10-31 20:48:49

+0

@Mark给我秒 – 2010-10-31 20:52:06

相关问题