c++ - 未知类型的模板模板参数

标签 c++ c++11 templates 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;
}

(作为问题的答案: Extract C++ template parameters ).

但是,有没有办法在不知道模板参数类型的情况下做到这一点。类似的东西(下面的代码无法编译...):

template <template<class SIZE_TYPE> class T, SIZE_TYPE K>
auto extractSize(const T<K>&) {
    return K;
}

上面的编译错误是:

error: unknown type name 'SIZE_TYPE'
template <template<class SIZE_TYPE> class T, SIZE_TYPE K>
                                             ^

最佳答案

auto 助您一臂之力!

template <template<auto> class T, auto K>
auto extractSize(const T<K>&) {
    return K;
}

这样,您作为模板参数传入的值的类型会自动推断出来。

关于c++ - 未知类型的模板模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48608830/

相关文章:

c++ - 交换对象不实现 move 语义时的交换函数

c++ - 以纳秒为单位存储时间戳 C++

c++ - 手动选择右值或左值类型的重载函数

c++ - 在 C++/boost 中的 *nix 中检索时间的最有效方法是什么?

c++ - 无论如何在模板参数上有一个decltype?

c++ - Xcode 8.3 不要求用户输入

c++ - 使用 auto&& 完美转发返回值

c++ - 如何创建通用函数,它将返回 C++ 中任何级别指针的值?

c++ - 为什么每个架构的 opensslconf.h 不同?

c# - 无法加载 DLL(找不到模块 HRESULT : 0x8007007E)