This question already has answers here:
Where and why do I have to put the “template” and “typename” keywords?

(6个答案)


2年前关闭。




给定一个整数模板参数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>();
                               ^

最佳答案

您需要 template disambiguator作为从属名称:

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

关于c++ - 搜索类的洋葱,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50286428/

10-17 01:27