如果没有声明constexpr,std::forward将丢弃constexpr-ness以用于转发参数的任何函数.为什么std::forward不宣布constexpr自己这样可以保留constexpr-ness?
示例:(使用g ++ snapshot-2011-02-19测试)
#include <utility>
template <typename T> constexpr int f(T x) { return -13;}
template <typename T> constexpr int g(T&& x) { return f(std::forward<T>(x));}
int main() {
constexpr int j = f(3.5f);
// next line does not compile:
// error: ‘constexpr int g(T&&) [with T = float]’ is not a constexpr function
constexpr int j2 = g(3.5f);
}
Run Code Online (Sandbox Code Playgroud)
注意:从技术上讲,很容易制作std::forwardconstexpr,例如,如此(请注意,g std::forward已被替换为fix::forward):
#include <utility>
namespace fix …Run Code Online (Sandbox Code Playgroud) 考虑以下具有单个数据成员和结构的结构 operator==
struct S {
int a;
/*constexpr*/ bool operator==(const S& other) const {
return this->a == other.a;
}
};
Run Code Online (Sandbox Code Playgroud)
在使用中,可以像constexpr初始化列表一样轻松创建两个结构
int main() {
constexpr S s1 = {1};
constexpr S s2 = {2};
constexpr bool b = s1 == s2; // error
return 0;
}
Run Code Online (Sandbox Code Playgroud)
bool比较无法编译,因为==运算符未标记为constexpr,如果是,程序编译.
是否所有类别的比较运算符都constexpr可以标记为constexpr?我没有看到任何理由,但我也没有看到代码练习这个.
我还会更进一步,询问是否operator*(S, S)应该一直constexpr这样.
我写了一个简单的例子来解决我在写他的程序时遇到的问题。
\n\n在程序执行期间,当从函数返回值时,我得到 input1 和 input2 的值,这些值永远不会改变。然后稍后,在程序过程中进行各种计算后,我得到一个结果,该结果也不再可变。
\n\n我正在尝试使用 switch-case 来比较它们,但出现一个错误“\xe2\x80\x98input1\xe2\x80\x99 的值在常量表达式中不可用”。
\n\n#include <iostream>\n\nusing namespace std;\n\nchar getChar()\n{\n char c;\n cin >> c;\n return c;\n}\n\nint main()\n{\n // it doesn\'t work\n const char input1 = getChar();\n const char input2 = getChar();\n\n // it it works\n //const char input1 = \'R\';\n //const char input2 = \'X\';\n\n char result = getChar();\n switch(result)\n {\n case input1:\n cout << "input1" << endl;\n break;\n case input2:\n cout << "input2" << endl;\n break;\n }\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n