如何暴露模板模板参数

3
假设我有以下类模板:
<> - 读作模板
template<template<class T> class Policy>
struct
{

};

如何(不添加其他参数到此<>中)向外界公开策略类型?
typedef不能工作,为什么我不能写类似这样的内容:

typedef Policy<T> Policy;

为什么我不能使用来自<<param>>的T类型?这个T类型是不可访问的吗?

这是C++0x中的typedef模板的工作。 - Alexandre C.
3个回答

1

类型T未定义。当您使用模板模板类型时,编译器期望一个不完整的类型,该类型可以与其他类型参数实例化。它不能用于提取类型。

template<template<typename T> class X> void func() {
};
func<std::shared_ptr>(); // correct usage
func<std::shared_ptr<int>>(); // fail

你知道这里所说的“不完整类型”的意思,但这可能会让人感到困惑,因为它正确的意思是一个前向声明的类型,尚未定义,或者是一个大小未知的数组或void。也许应该称之为“模板名称”? - j_random_hacker

1

我知道在C++0x中是可能的,但我不知道语法。与此同时,在C++03中最接近的匹配是

template <template <typename> Pol>
struct Foo
{
    template <typename T>
    struct policy
    {
        typedef Pol<T> type;
    };
};

用法:typename Foo<F>::template policy<T>::type,在您本来想写Foo::policy<T>的地方使用。


0

正如DeadMG所说,模板模板类型是不完整的。例如,不完整类型std::vector匹配template< template<class, class> class TypeWithTwoParams>

为了推导出您示例中T的实际类型,您可以向函数提供一个具有“完整类型”的参数。例如,在下面的代码中,我们可以推断出T,因为我们将arg作为参数传递给PolicyRelatedFunction,并且它具有完整类型,这使得编译器能够进行必要的推断。

我觉得这就是您想做的事情,只是用函数而不是结构体。typeid的东西只是为了说明我们可以使用T。这将打印出“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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接