有没有办法将参数转发给内部constexpr函数? [英] Is there a way to forward argument to inner constexpr function?

查看:84
本文介绍了有没有办法将参数转发给内部constexpr函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:是否可以通过将其参数传递给内部constexpr函数来对函数内部的常量表达式求值?
示例:

The question: is it possible to evaluate constant expression inside a function by passing (maybe with some kind of "perfect forwarding") its argument to inner constexpr function? Example:

constexpr size_t foo(char const* string_literal) {
    return /*some valid recursive black magic*/;
}

void bar(char const* string_literal) {
    // works fine
    constexpr auto a = foo("Definitely string literal.");
    // compile error: "string_literal" is not a constant expression
    constexpr auto b = foo(string_literal);
}

template<typename T>
void baz(T&& string_literal) {
    // doesn't compile as well with the same error
    constexpr auto b = foo(std::forward<T>(string_literal));
}

int main() {
    // gonna do this, wont compile due to errors mentioned above
    bar("Definitely string literal too!");
}

文档,但找不到解决方案,也无法证明。内部表达式的构造性很重要。

Can't find anything clearly prohibiting in the documentation, but the solution isn't found, as well as a proof of impossibility. Constexpr'ness of inner expression is important.

推荐答案

constexpr 的参数在 constexpr 函数中不能将函数假定为 constexpr ;如果不是 constexpr ,则该函数必须正常工作。

Parameters to constexpr functions cannot be assumed to be constexpr within a constexpr function; the function must work if they are not constexpr.

类型参数可以。

如果您将 bar( hello)替换为 bar(string_constant<'h ','e','l','l','o'> {}) template< char ...> struct string_constant {}; ,现在将字符值编码在类型中,并且在路径中可用。还有其他方法可以将字符转换为类型。

If you replaced bar("hello") with bar( string_constant<'h', 'e', 'l', 'l', 'o'>{} ) with template<char...>struct string_constant{};, the value of the characters is now encoded in the type and will be available down the path. There are other ways to get the characters into a type.

这篇关于有没有办法将参数转发给内部constexpr函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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