Tro*_*iar 11 c++ constexpr perfect-forwarding c++11
问题:是否有可能通过将其参数传递给内部constexpr函数(可能带有某种"完美转发")来评估函数内部的常量表达式?例:
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!");
}
Run Code Online (Sandbox Code Playgroud)
constexpr函数的参数不能假定constexpr在constexpr函数内; 如果不是,constexpr该功能必须有效.
类型参数可以是.
如果替换bar("hello")为bar( string_constant<'h', 'e', 'l', 'l', 'o'>{} )with template<char...>struct string_constant{};,则字符的值现在按类型编码,并且在路径下可用.还有其他方法可以将字符转换为类型.