小编fda*_*dan的帖子

您可以在编译时将 std::vector 转换为 std::array 而不使向量两次吗?

我正在编译时使用计算一些数据std::vector,并希望将结果作为数组返回,以便可以在运行时进一步使用。我在不进行两次计算的情况下设置数组大小时遇到​​问题。

这是我迄今为止所做的事情的简化示例。代码按预期编译并运行。

constexpr auto make_vector() { 
  // complex calculation here
  return std::vector{1, 2, 3}; 
}

constexpr auto make_array() {
  const auto vec = make_vector();
  std::array<int, make_vector().size()> result{};

  std::copy(vec.cbegin(), vec.cend(), result.begin());
  return result;
}

int main() {
  constexpr auto result = make_array(); // std::array<int, 3>{1, 2, 3}
}
Run Code Online (Sandbox Code Playgroud)

我理解为什么不能用于vec.size()数组大小以及为什么make_vector().size()会产生编译时常量。做两次似乎不是正确的方法。

有没有办法避免调用make_vector两次?我在这里错过了一个基本概念吗?

c++ constexpr c++20

19
推荐指数
1
解决办法
1108
查看次数

using 命名空间指令是否使名称在内联函数中可用?

考虑声明一个不受约束的ns::operator*. using namespace ns在块作用域中并调用函数之后foo<T>,clangns::operator*在读取内部基于范围的循环的迭代器时使用foo。没有其他类型ns涉及其他类型,因此 ADL 应该不会产生任何候选者。

在以下示例中,static_assert失败并显示消息:

错误:由于要求 'std::is_same_v<const int &, const custom_type &>',静态断言失败

汇编代码显示这ns::operator*是由 clang 使用的。gcc 和 msvc 的断言都通过了!

namespace ns {

template <typename T>
constexpr auto operator*(T&& /*value*/) {
    struct custom_type {};
    return custom_type{};
};

}  // namespace ns

template <typename T>
constexpr void foo() {
    std::vector<T> vec{};
    for (const auto& curr : vec) {
        static_assert(std::is_same_v<const T&, decltype(curr)>);
    }
}

int main() { …
Run Code Online (Sandbox Code Playgroud)

c++ templates namespaces using compiler-bug

6
推荐指数
1
解决办法
149
查看次数

标签 统计

c++ ×2

c++20 ×1

compiler-bug ×1

constexpr ×1

namespaces ×1

templates ×1

using ×1