我有这个片段。
#include <iostream>
#include <string>
struct JustStr {
JustStr(const std::string& x) : val(x) {}
static constexpr bool pred = false;
std::string val;
};
template <typename T>
class C {
private:
T x;
public:
C(T x_) : x(x_) {}
void f() {
if constexpr (!x.pred) {
std::cout << x.val << std::endl;
}
}
};
template<typename T>
void f2(T x) {
T y(x);
if constexpr (!y.pred) {
std::cout << x.val << std::endl;
}
}
int main() {
C<JustStr> c(JustStr("yes"));
c.f(); // Fails
f2(JustStr("yes")); // Succeeds
return 0;
}
我的问题是:不应该c.f();
同时f2(JustStr("yes"));
失败或成功吗?为什么一个失败,另一个为什么成功?