【问题标题】:Access templated "using" in templated parent class在模板化父类中访问模板化“使用”
【发布时间】:2021-02-11 10:38:32
【问题描述】:

我有一个这样的类层次结构:

/* Base templated interface class */
template <class T>
class InterfaceClass {
  public:
    // Normal using sentence
    using InnerType1 = SomeClass<T>;

    // HERE1: Templated using sentence that I want to use in other places
    template<typename SomeType>
    using TplInnerType = SomeOtherClass<InnerType1, SomeType>; 
};

/* Some templated intermediate class inheriting from the interface */
template <typename T>
class Class : InterfaceClass<T> {
  public:
    using BaseType = InterfaceClass<T>;

    // This works
    using typename BaseType::InnerType1;

    // HERE2: This won't work in any form
    using typename BaseType::TplInnerType;
};

/* Then I have some children using the CRTP as: */
class Child1 : Class<Child1> { ... };
class Child2 : Class<Child2> { ... };

我想在后代 (HERE2) 中使用来自 InterfaceClass 的模板化 using 语句 (HERE1),但我无法让编译器 (C++11 over clang 10) 解析类型。 我按照编译器的建议尝试了许多组合,包括:

  template <typename U> using typename BaseType::TplInnerType<U>;
  template <typename U> using TplInnerType = BaseType::TplInnerType<U>;
  template <typename U> using TplInnerType = typename BaseType::TplInnerType<U>;
  template <typename U> using TplInnerType = BaseType::template TplInnerType<U>;

但是建议让我转了一圈……我尝试做的事情是否可能?

编辑 - 另一个解决方案

除了@Jarod42 answer,它适用于这个玩具示例但不适用于我的真实案例,我找到了另一个有效的解决方案 (sample):

template <typename T>
class Class : InterfaceClass<T> {
  public:
    using BaseType = InterfaceClass<T>;
    using typename BaseType::InnerType1;
    // This works
    template <typename U>
    using TplInnerType = typename BaseType::template TplInnerType<U>;
};

【问题讨论】:

  • 由于Class已经使用T,您可以使用其他名称(如U)作为模板参数。
  • 你也错过了一些公众...
  • 元编程真是个丑陋的东西......
  • @Jarod42 是的,是的。我已经更改了示例代码以反映这些......原始代码不会遇到这个问题。

标签: c++ c++11 templates


【解决方案1】:

你应该放弃typename

template <typename T>
class Class : public InterfaceClass<T> {
public:
  using BaseType = InterfaceClass<T>;
  using typename BaseType::InnerType1;
  using BaseType::TplInnerType;
};

Demo

【讨论】:

  • 好的,我遗漏了一些东西,因为它在原始代码中不起作用。但我找不到有什么区别。目前我接受这个答案,因为它确实解决了问题中所述的问题。我稍后会回来。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-10
相关资源
最近更新 更多