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

car*_*rlo 5 stdvector variadic-templates c++11

我正在试验 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);
}
Run Code Online (Sandbox Code Playgroud)

代码编译并按预期运行(我使用了 gcc 4.6)。我想问以下问题:

  1. 我用扩展的参数包( vector v {static_cast(args)...}; )初始化了一个 std::vector 。这是正确的 C++11 吗?我还没有在任何地方找到这个功能的解释。
  2. 我不太喜欢 all_true 的声明,因为我知道类型但我使用模板。是否可以使用类似于以下内容的内容?

    constexpr bool all_true(bool head, bool... tail){...} // This code doesn't compile
    
    Run Code Online (Sandbox Code Playgroud)

谢谢!

Rei*_*ica 3

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

    \n\n
    \n

    ... 包扩展可能发生在以下环境中:\n ...

    \n\n
      \n
    • 初始化列表中(8.5);该模式是一个初始化子句。
    • \n
    \n
  2. \n
  3. 不,没有办法创建非模板类型安全的可变参数函数。你所拥有的就可以了。有一个关于这个的问题

  4. \n
\n