未知类型的模板模板参数 [英] template template parameter of unknown type

查看:49
本文介绍了未知类型的模板模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在以下代码中提取模板参数值:

Trying to extract template parameter value in the following code:

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;
}

(作为问题的答案:
提取C ++模板参数)。

(As an answer for the question: Extract C++ template parameters).

但是有一种方法无需知道模板参数的类型。诸如此类(下面的代码无法编译...):

However, is there a way to do it without knowing the type of the template parameter. Something like (code below doesn't compile...):

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>
                                             ^


推荐答案

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

这样,将自动推断您作为模板参数传递的值的类型。

That way the type of the value you passed in as template parameter is automatically inferred.

这篇关于未知类型的模板模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆