【问题标题】:Search in an onion of class [duplicate]在洋葱类中搜索[重复]
【发布时间】:2018-05-11 06:39:53
【问题描述】:

给定一个整数模板参数Key,搜索方法应该在编译期间提取具有key == Key的洋葱层。

如何修复搜索方式?

测试(也在godbolt.org

#include <iostream>

class A {
public:
    static constexpr int key = 0;
    template<int s>
    constexpr auto& search() const { return *this; }
};

template<class P>
class B {
public:
    static constexpr int key = P::key + 1;
    template <int Key>
    constexpr auto& search() const {
        if constexpr (Key == key) return *this;
        return p_.search<Key>();
    }
    P p_;
};

int main() {
    B<B<B<B<A>>>> onion;
    std::cout << onion.search<1>().key << "\n";
    return 0;
}

错误:

error: expected primary-expression before ‘)’ token
         return p_.search<Key>();
                               ^

【问题讨论】:

  • 只适用于D&lt;C&lt;B&lt;A&gt;&gt;&gt;C&lt;D&lt;B&lt;A&gt;&gt;&gt;BCD 的其他排列的搜索就可以了。

标签: c++ templates c++17


【解决方案1】:

您需要 template disambiguator 作为依赖名称:

constexpr auto& search() const {
    if constexpr (Key == key) {
        return *this;
    } else {
        return p_.template search<Key>();
                  ^^^^^^^^
    }
}

【讨论】:

  • @Rzu 我以为是你的错字......但我已经在我的回答中修正了它。
  • @Swift 你对ifif constexpr 感到困惑,if constexpr 只会选择正确的分支进行编译。这里没有其他问题。
  • @liliscent 我的错。我不习惯支持它的编译器。我总是想知道为什么如果其中的表达式是constexpr,则不能推断为constexpr
  • 哈。它似乎工作。谢谢。
猜你喜欢
  • 2011-10-09
  • 2018-07-28
  • 2014-10-15
  • 1970-01-01
  • 1970-01-01
  • 2015-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多