在班级的洋葱中搜索

R z*_* zu 6 c++ templates c++17

给定整数模板参数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;
}
Run Code Online (Sandbox Code Playgroud)

错误:

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

lll*_*lll 6

你需要template消除歧义的依赖名称:

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

  • @Swift你对`if`和`if constexpr`感到困惑,``constexpr`只会选择正确的分支进行编译.这里没有其他问题. (3认同)