请考虑以下代码:
static constexpr int make_const(const int i){
return i;
}
void t1(const int i)
{
constexpr int ii = make_const(i); // error occurs here (i is not a constant expression)
std::cout<<ii;
}
int main()
{
t1(12);
}
Run Code Online (Sandbox Code Playgroud)
为什么我在make_const调用时出错?
UPDATE
但是这个有效:
constexpr int t1(const int i)
{
return make_const(i);
}
Run Code Online (Sandbox Code Playgroud)
但是,这不是:
template<int i>
constexpr bool do_something(){
return i;
}
constexpr int t1(const int i)
{
return do_something<make_const(i)>(); // error occurs here (i is not a constant expression)
}
Run Code Online (Sandbox Code Playgroud) 问题:是否有可能通过将其参数传递给内部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 …Run Code Online (Sandbox Code Playgroud) 我可以强制编译器只接受constexpr函数的一个或非变量输入吗?
我正在寻找只允许编译函数的时间值.使用模板或任何其他方法.
这里有一个int模板的工作示例.doubles 的问题是它们不能用作模板参数.
#include <iostream>
template <double x>
void show_x()
{
std::cout<<"x is always "<<x<<" in the entire program."<<std::endl;
}
int main()
{
show_x<10.0>();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
错误:'double'不是模板非类型参数的有效类型
更新
对于那些将此问题标记为重复的人,我不得不说:
我问问题
如何解决问题A?
和
解决方案B不适用于问题A,我需要另一种解决方案
然后你链接我为什么解决方案B不起作用.
那是完全不合逻辑的.
我有这段代码:
template <int V>
struct Constant {
constexpr operator int() const noexcept { return V; }
};
template <class T, int N>
struct Array { };
auto function(auto s) -> Array<int, s + s> {
return {};
}
auto const a = function(Constant<3>{});
Run Code Online (Sandbox Code Playgroud)
让我最悲伤的是,似乎只有 Clang 接受这个代码。
哪个编译器是正确的,为什么?