How to expose template template arg
Let's assume that I have following cl开发者_开发技巧ass template:
<> - read as templatetemplate<template<class T> class Policy>
struct
{
};
How (without adding additional params to this <>) can I expose Policy type to external world?
typedef won't work, and why for the loG can't I write something like this:typedef Policy<T> Policy;
Why can't I use the T type from << param>>? Is this T type unaccessible?
I know it is possible with C++0x, but I don't know the syntax. In the meantime, the closest fit in C++03 is
template <template <typename> Pol>
struct Foo
{
template <typename T>
struct policy
{
typedef Pol<T> type;
};
};
usage: typename Foo<F>::template policy<T>::type
where you would have wanted to write Foo::policy<T>
.
The T type is undefined. When you take a template template type, the compiler expects an incomplete type that may be instantiated with other type parameters. It doesn't serve to extract the type.
template<template<typename T> class X> void func() {
};
func<std::shared_ptr>(); // correct usage
func<std::shared_ptr<int>>(); // fail
As DeadMG said, a template template type is incomplete. For example, the incomplete type std::vector matches template< template<class, class> class TypeWithTwoParams>
In order to deduce the actual type of T in your example, you could provide an argument (which has "complete type") to a function. For example, in the code below we can deduce T because we're passing in arg as an argument to PolicyRelatedFunction and it has complete type which allows the compiler to make the necessary deductions.
I get the feeling this is what you're trying to do, except with a function rather than a struct. The typeid stuff is just there to illustrate that we can use T. This will print out "T = std::string"
template< template<class > class Policy, typename T>
void PolicyRelatedFunction(Policy<T>& arg)
{
if (typeid(T) == typeid(int) )
std::cout << "T = int";
else if (typeid(T) == typeid(std::string) )
std::cout << "T = std::string";
}
TemplatedType<std::string> arg;
PolicyRelatedFunction<TemplatedType>(arg);
// PolicyRelatedFunction(arg) works as well - compiler can figure it out.
精彩评论