【问题标题】:Referencing to the nested template parameter引用嵌套模板参数
【发布时间】:2015-01-15 10:50:13
【问题描述】:

我需要一个模板类,但问题是,我无法访问嵌套模板的类型:

template<template<class TParamPayload> class TMsg>
class ParameterBasedFilter : public IMsgFilter
{
public:
    typedef TMsg<TParamPayload> ExpectedMessage;
    typedef TParamPayload::otherType SomeOtherType;
};

这是一个用法(我只想传递一个模板参数,不带逗号)

ParameterBasedFilter<SomeMessage<SomePayload>> filter;

ParameterBasedFilter内部有错误:

error: 'TParamPayload' was not declared in this scope
typedef TMsg<TParamPayload> ExpectedMessage;
             ^

是否有可能获得嵌套模板类型?我知道,下面的代码可以工作

template<class TParamPayload, template<class> class TMsg>
class ParameterBasedFilter : public IMsgFilter
{
public:
    typedef TMsg<TParamPayload> ExpectedMessage;
    typedef TParamPayload::otherType SomeOtherType;
};

但是我必须将 2 种类型传递给模板参数:

ParameterBasedFilter<SomePayload, SomeMessage<SomePayload>> filter;

而且看起来很奇怪,因为 SomePayload 被使用了两次。

【问题讨论】:

标签: c++ templates


【解决方案1】:

也许您正在寻找部分专业化?这将允许您的问题中提到的原始语法:

template <typename> class ParameterBasedFilter;

template <template<class> class TMsg, typename TParamPayload>
class ParameterBasedFilter<TMsg<TParamPayload>> : public IMsgFilter
{
public:
    typedef TMsg<TParamPayload> ExpectedMessage;
    typedef TParamPayload::otherType SomeOtherType;
};

用法很简单:

ParameterBasedFilter<SomeMessage<SomePayload>> filter;

【讨论】:

  • 当他希望传递给ParameterBasedFilter 的类型为TMsg&lt;TParamPayload&gt; 时,这绝对是解决方案。否则,只需使用普通的template &lt;typename T&gt;
  • @JorenHeit 你是什么意思?
  • 如果他只是想让用例起作用,他不妨使用template &lt;typename T&gt;(你的非专业案例)。但是,要获得嵌套类型,他必须确保有一个嵌套的typedef 来定义有效负载参数,因此您的解决方案更好:-)(尽管适用于所有类似 STL 的容器)。
  • @JorenHeit 您的意思是,不适用于类似 STL 的容器?好吧,在这种情况下,可以使用可变参数模板模板参数。
  • 哈哈不,我不是这个意思。我的意思是,如果 TMsg 类定义了 STL 的 value_type 的等价物(因此定义了 TParamPayload),那么无需专门化就可以得到这样的类型。也就是说,您的解决方案可能更通用、更优雅。
【解决方案2】:

不,你不能。但是你应该通过

ParameterBasedFilter<SomePayload, SomeMessage> filter;

SomePayload 不会被使用两次。 另外,访问otherType时应该使用typename

typedef typename TParamPayload::otherType SomeOtherType;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多