【问题标题】:CRTP derived templated method call yields expected primary-expression before ‘>’ token [duplicate]CRTP 派生的模板化方法调用在“>”标记之前产生预期的主表达式 [重复]
【发布时间】:2020-08-03 20:41:42
【问题描述】:

以下示例无法编译并出现错误error: expected primary-expression before ‘>’ token。我不理解为什么。我正在尝试调用派生的 CRTP 模板化方法。我用 CRTP 这样做是因为你不能有 virtual 模板化方法。

https://godbolt.org/z/PMfsPM

#include <iostream>
#include <memory>
#include <type_traits>

struct Foo
{
  Foo(int xx, int yy) : x(xx), y(yy) {}
  int x, y;
};
struct Bar
{
  Bar(int xx, int yy, int zz) : x(xx), y(yy), z(zz) {}
  int x, y, z;
};

template<class Derived = void>
class Base
{
public:
  template<class T>
  std::unique_ptr<T> makeTImpl(int x, int y) {
    return std::make_unique<T>(x, y);
  }
  template<class T>
  std::unique_ptr<T> makeT(int x, int y)
  {
    if constexpr (std::is_same_v<Derived, void>) {
      return makeTImpl<T>(x, y);
    } else {
      auto& d = *static_cast<Derived*>(this);
      return d.makeTImpl<T>(x, y); // error: expected primary-expression before ‘>’ token
    }
  }
};

class Derived : public Base<Derived>
{
public:
  Derived(int z) : _z(z) {}

  template<class T>
  std::unique_ptr<T> makeTImpl(int x, int y) {
    return std::make_unique<T>(x, y, _z);
  }
private:
  int _z;
};

int main() {
  Base b;
  b.makeT<Foo>(1, 2);
  Derived d(3);
  d.makeT<Bar>(1, 2);
}

【问题讨论】:

  • @JeJo 我主要在寻找“CRTP 模板化方法覆盖调用”或类似的东西。这是未来搜索者的另一个热门!

标签: c++ templates crtp


【解决方案1】:

makeTImpl 是一个函数模板,用于依赖上下文。所以而不是:

d.makeTImpl<T>(x, y);

你需要写:

d.template makeTImpl<T>(x, y);
//^^^^^^^^

这是demo

有关哪些上下文需要template 关键字的详细信息,请参阅此post

【讨论】:

    猜你喜欢
    • 2016-07-24
    • 2016-10-26
    • 1970-01-01
    • 2013-08-29
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多