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>();
^
You need template
disambiguator for dependent name:
constexpr auto& search() const {
if constexpr (Key == key) {
return *this;
} else {
return p_.template search<Key>();
^^^^^^^^
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With