Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search in an onion of class [duplicate]

Given an integer template parameter Key, the search method should extract a layer of the onion that has key == Key during compilation.

How to fix the search method?

Test (also at 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:

error: expected primary-expression before ‘)’ token
         return p_.search<Key>();
                               ^
like image 868
R zu Avatar asked May 11 '18 06:05

R zu


1 Answers

You need template disambiguator for dependent name:

constexpr auto& search() const {
    if constexpr (Key == key) {
        return *this;
    } else {
        return p_.template search<Key>();
                  ^^^^^^^^
    }
}
like image 87
llllllllll Avatar answered Nov 15 '22 01:11

llllllllll