模板非类型参数推导 [英] Template non-type parameter deduction

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

问题描述

是否可以推断出c ++ 17函数的模板值(非类型)?

Is it possible to deduce template value (not type) for a c++17 function?

函数foo:

template<int I>
int foo()
{
    return (I);
}

可以通过以下方式调用:

Can be called via:

foo<5>();

并返回5。

模板类型可以通过函数参数的类型来推导。是否可以以某种方式对模板值执行相同操作?例如:

Template types can be deduced through the type of a function argument. Is it possible to do the same in some way for the template value? For example:

template<int I = x>
int bar(const int x)
{
    return (I);
}

这显然行不通(因为一个 x 在声明之前是必需的),但是可能会有一些C ++ 17技巧可以实现这一点吗?

This obviously wont work (because for one x is required before its declaration), but might there be some C++17 trick which would allow for this?

我想使用

推荐答案

只能通过(ab)使用类型来完成所需的操作扣除为整数扣除。观察:

What you want can only be done by (ab)using type deduction for integer deduction. Observe:

template<int x>
struct integer_value {};

template<int x>
void test(integer_value<x> val)
{
  //x can be used here.
}

当然,您必须使用 test( integer_value< 4> {})或类似的东西。

Of course, you must invoke this with test(integer_value<4>{}) or something similar.

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

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