【发布时间】:2017-03-20 15:28:49
【问题描述】:
这个(虚构的)问题最初被表述为一个谜题,隐藏 一些可能有助于更快地发现问题的细节。向下滚动 对于更简单的MCVE 版本。
原始(拼图)版本
我有这段代码输出0:
#include <iostream>
#include <regex>
using namespace std;
regex sig_regex("[0-9]+");
bool oldmode = false;
template<class T>
struct B
{
T bitset;
explicit B(T flags) : bitset(flags) {}
bool foo(T n, string s)
{
return bitset < 32 // The mouth is not full of teeth
&& 63 > (~n & 255) == oldmode // Fooness holds
&& regex_match(s, sig_regex); // Signature matches
}
};
template<class T>
struct D : B<T>
{
D(T flags) : B<T>(flags) {}
};
int main()
{
D<uint64_t> d(128 | 16 | 1);
cout << d.foo(7, "123") << endl;
}
但是,当我将函数 foo() 从 B 移动到 D 时,它开始输出 1 (proof is on Coliru)。
为什么会这样?
MCVE 版本
#include <iostream>
#include <bitset>
using namespace std;
template<class T>
struct B
{
T bitset{0};
bool foo(int x)
{
return bitset < 32 && 63 > (x + 1) == x % 2;
}
};
template<class T>
struct D : B<T>
{
bool bar(int x) // This is identical to B<T>::foo()
{
return bitset < 32 && 63 > (x + 1) == x % 2;
}
};
int main()
{
D<uint64_t> d;
cout << d.foo(1) << endl; // outputs 1
cout << d.bar(1) << endl; // outputs 0; So how is bar() different from foo()?
}
【问题讨论】:
-
foo中的return表达式的哪一位发生了变化? -
这是一个有效的主题问题;关闭投票不正确。
-
代码示例是否应该是不必要的非最小化和混乱?如果没有,我建议只包含
<bitset>并摆脱整个regexred herring。 -
您应该在发布之前尝试简化此代码。
-
"[...] 这是否意味着作为测试 [...]" --> "否[...]" --> "[...] 问题最初是制定的作为一个谜题[...]”。我不知道 stackoverflow 是否适合在不回答的情况下提出您已经知道答案的问题,同时让发现问题变得更加困难。
标签: c++ c++11 templates namespaces