小编Yon*_* Wu的帖子

在 constexpr 构造函数中初始化数组是否合法?

下面的代码合法吗?

template <int N>
class foo {
public:
    constexpr foo()
    {
        for (int i = 0; i < N; ++i) {
            v_[i] = i;
        }
    }

private:
    int v_[N];
};

constexpr foo<5> bar;
Run Code Online (Sandbox Code Playgroud)

Clang 接受它,但 GCC 和 MSVC 拒绝它。

GCC 的错误是:

main.cpp:15:18: error: 'constexpr foo<N>::foo() [with int N = 5]' called in a constant expression
   15 | constexpr foo<5> bar;
      |                  ^~~
main.cpp:4:15: note: 'constexpr foo<N>::foo() [with int N = 5]' is not usable as a 'constexpr' function because:
    4 …
Run Code Online (Sandbox Code Playgroud)

c++ compile-time-constant template-meta-programming constexpr

13
推荐指数
1
解决办法
839
查看次数

隐式转换应该在模板参数的上下文中工作吗?

更明确地说,编译器是否应该将true_type值视为true的第一个参数enable_if,因为true_type是真的std::integral_constant<bool, true>,并integral_constant定义了类型转换函数operator value_type

下面是最简单的测试代码:

#include <type_traits>

template <typename T>
std::enable_if_t<std::is_pod<T>{}>
test(T)
{
}

int main()
{
    test(true);
}
Run Code Online (Sandbox Code Playgroud)

它被 GCC 和 Clang 接受,但被 MSVC 拒绝(直到 Visual Studio 2019 v16.3.1)。

c++ templates language-lawyer implicit-conversion non-type

3
推荐指数
1
解决办法
121
查看次数

C++ 概念相同且可赋值

我最近一直在尝试 C++ 概念。我正在尝试以下范围扩展文档中的定义:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4569.pdf

的定义和用法Same让我感到困惑。由于我不知道的原因,作者没有给出明确的定义。所以我正在使用:

template <class T, class U>
concept bool Same()
{
  return std::is_same<T, U>::value;
}
Run Code Online (Sandbox Code Playgroud)

问题是该文档给出了以下定义Assignable

template <class T, class U>
concept bool Assignable()
{
  return Common<T, U>() && requires(T&& a, U&& b) {
    { std::forward<T>(a) = std::forward<U>(b) } -> Same<T&>;
  };
}
Run Code Online (Sandbox Code Playgroud)

它不起作用(在 GCC 6.3 下):一个简单的Assignable<int&, int&&>()概念检查给了我false(我已经验证该Common部分没问题)。我必须更改Same<T&>才能T&使其看起来有效。同样的Same<Type>检查也用在其他一些地方。

我的问题是:

  • 我的定义Same正确吗?
  • 为什么Same<T&>用 代替T&?有什么区别?

谢谢你的帮助。

c++ c++-concepts

2
推荐指数
1
解决办法
1037
查看次数