gpt4 book ai didi

c++11 - 我们可以使用参数包作为 std::vector 初始值设定项吗?

转载 作者:行者123 更新时间:2023-12-01 02:21:12 24 4
gpt4 key购买 nike

我正在试验 C++11(到目前为止我已经使用了旧的 C++)并且我编写了以下代码:

#include <iostream>
#include <vector>
#include <type_traits>

using namespace std;

constexpr bool all_true(){
return true;
}

template <typename Head, typename... Tail>
constexpr bool all_true(Head head, Tail... tail){
static_assert( is_convertible<bool, Head>::value, "all_true arguments must be convertible to bool!");
return static_cast<bool>(head) && all_true(tail...);
}

template<typename T, typename... Args>
void print_as(Args... args){
static_assert( all_true(is_convertible<T,Args>::value...), "all arguments must be convertible to the specified type!");
vector<T> v {static_cast<T>(args)...};
for(T i : v) cout << i << endl;
}

int main(){
print_as<bool>(1, 2, 0, 4.1);
}

代码编译并按预期运行(我使用了 gcc 4.6)。我想问以下问题:
  • 我用扩展的参数包( vector v {static_cast(args)...}; )初始化了一个 std::vector 。这是正确的 C++11 吗?我还没有在任何地方找到这个功能的解释。
  • 我不太喜欢 all_true 的声明,因为我知道类型但我使用模板。是否可以使用类似于以下内容的内容?
    constexpr bool all_true(bool head, bool... tail){...} // This code doesn't compile

  • 谢谢!

    最佳答案

  • 是的,可以在初始化列表中使用包扩展。 C++11 [temp.variadic]§4 允许这样做:

    ... Pack expansions can occur in the following contexts: ...

    • In an initializer-list (8.5); the pattern is an initializer-clause.
  • 不,没有办法制作非模板类型安全的可变参数函数。你有什么就可以了。有一个 question about this最近。
  • 关于c++11 - 我们可以使用参数包作为 std::vector 初始值设定项吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20423080/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com