可以通过编译时已知的对象创建类型(或实例化模板)吗?
假设我有一个模板函数:
template <typename T, T value>
auto foo(std::integral_constant<T, value>)
{
if constexpr (value == 0)
{
return int{};
}
else
{
return float{};
}
}
我想使用数字常量来调用它:
foo(4);
可以实现吗?如果没有,为什么?
我发现我可以自己创建 std::integral_constant
,但我对从对象创建类型的想法感兴趣。在上面的示例中,我将 4
作为对象,将 std::integral_constant
作为类型。
声明一些 define
来执行 if
或 switch
并不是一个解决方案 - 它会包含大量代码并且速度很慢。
Suppose I have a template function:
template <typename T, T value>
auto foo(std::integral_constant<T, value>)
{
if constexpr (value == 0)
{
return int{};
}
else
{
return float{};
}
}
And I want to call it using a number constant:
foo(4);
Can it be implemented? If no, why?
I see that I can create std::integral_constant
on my own, but I'm interested in the idea of creating a type from an object. In the example above, I have 4
as the object and std::integral_constant
as the type.
Declaring some define
which will do if
or switch
is not a solution - it will be a lot of code and slow.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是函数的调用语法:
但是您不需要
integral_constant
。您可以简化为:但从您的描述来看,这也不是您真正想要的。虽然不是很清楚,但看起来您想要一个基于值的类型。如果是这种情况,那么您需要类型别名,而不是函数,因为函数返回值而不是类型。
这是类型别名版本:
This is the calling syntax for your function:
However you don't need the
integral_constant
. You can simplify to this:But from your description even that is not what you actually want. Although is not very clear it looks like you want a type based on a value. If that is the case then you need a type alias, not a function, because functions return values and not types.
Here is the type alias version:
我绝对不推荐这样做,但您可以使用宏来实现您想要的语法:
演示
最终你最好暂时坚持bolov的答案直到constexpr 函数参数 (P1045) 已标准化(或类似的东西)。
I absolutely do not recommend this, but you could use a macro to achieve the syntax you're after:
Demo
Ultimately you're better sticking to bolov's answer for now until constexpr function parameters (P1045) is standardized (or something similar to it).