我有幸遇到的最让我最喜爱/最邪恶的发明之一是constexpr计数器,也就是有状态的元编程.正如帖子中所提到的,它似乎在C++ 14下是合法的,我想知道C++ 17有什么变化吗?
以下是主要基于帖子的实现
template <int N>
struct flag
{
friend constexpr int adl_flag(flag<N>);
constexpr operator int() { return N; }
};
template <int N>
struct write
{
friend constexpr int adl_flag(flag<N>) { return N; }
static constexpr int value = N;
};
template <int N, int = adl_flag(flag<N>{})>
constexpr int read(int, flag<N>, int R = read(0, flag<N + 1>{}))
{
return R;
}
template <int N>
constexpr int read(float, flag<N>)
{
return N;
}
template <int N …Run Code Online (Sandbox Code Playgroud) 愚蠢的问题。谁能向我解释一下这段代码是如何工作的?(从这里https://alexpolt.github.io/type-loophole.html)
#include <string>
#include <type_traits>
template<int N> struct tag{};
template<typename T, int N>
struct loophole_t {
friend auto loophole(tag<N>) { return T{}; };
};
auto loophole(tag<0>);
int main() {
sizeof( loophole_t<std::string, 0> );
static_assert(std::is_same< std::string, decltype( loophole(tag<0>{}) ) >::value);
}
Run Code Online (Sandbox Code Playgroud)
看起来sizeof( loophole_t<std::string, 0> );影响编译器全局状态。我的意思是如果我们删除这条线static_asserts失败。在 C++ 中允许吗?
更新:刚刚意识到这取决于编译器甚至编译器版本。适用于任何 GCC >=8(可能也适用于旧版本)。不能用 clang >= 10 编译,但在 clang 7.0 下工作正常
所以我想说我真正的问题是编译器错误还是标准行为?