【发布时间】: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<C<B<A>>>、C<D<B<A>>>和BCD的其他排列的搜索就可以了。