Ami*_*rsh 8 c++ templates c++11 c++14
尝试在以下代码中提取模板参数值:
template<std::size_t SIZE>
class Foo {};
template <template<std::size_t> class T, std::size_t K>
auto extractSize(const T<K>&) {
return K;
}
int main() {
Foo<6> f1;
Foo<13> f2;
std::cout << extractSize(f1) << std::endl;
std::cout << extractSize(f2) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
(作为问题的答案: 提取C++模板参数).
但是,有没有办法在不知道模板参数类型的情况下执行此操作.类似的东西(下面的代码不能编译......):
template <template<class SIZE_TYPE> class T, SIZE_TYPE K>
auto extractSize(const T<K>&) {
return K;
}
Run Code Online (Sandbox Code Playgroud)
编译错误:
error: unknown type name 'SIZE_TYPE'
template <template<class SIZE_TYPE> class T, SIZE_TYPE K>
^
Run Code Online (Sandbox Code Playgroud)
auto 救援!
template <template<auto> class T, auto K>
auto extractSize(const T<K>&) {
return K;
}
Run Code Online (Sandbox Code Playgroud)
这样,您自动推断作为模板参数传递的值的类型.