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)
你需要template消除歧义的依赖名称:
constexpr auto& search() const {
if constexpr (Key == key) {
return *this;
} else {
return p_.template search<Key>();
^^^^^^^^
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
205 次 |
| 最近记录: |