In code:
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;
}
Edited [for Mark H]
template<class T, template<class> class Policy = FactorPolicy>
struct Map : Policy<double>
{
Map(double value):Policy<double>(value)
{
}
};
One way is to provide member function templates that take a template arg to use with the policy. For example:
template<class T, template<class> class Policy = FactorPolicy>
struct Map
{
template <typename V>
void foo(const Policy<V> &p)
{
}
};
Then, in main:
Map<int,FactorPolicy> m;
m.foo(FactorPolicy<double>(5.0));
Another possibility is to specify it as part of Map template instantiation, by adding a third template arg to Map:
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);
If you were to pass a double, it would require that the type argument of FactorPolicy be double inside Map, unless you make the FactorPolicy constructor to accept a double. I don't think that is what you want though. You must inform Map that Policy needs a double, so first add that type argument. Secondly, I think you will need to forward the actual double value from the Map constructor.
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;
}
精彩评论