我们可以使用参数包作为std :: vector初始化器吗?

时间:2013-12-06 11:46:10

标签: c++11 stdvector variadic-templates

我正在尝试使用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)。我想问一下以下问题:

  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
    
  3. 谢谢!

1 个答案:

答案 0 :(得分:3)

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

      

    ...包扩展可以在以下上下文中发生:   ...

         
        
    • 初始化列表(8.5)中;模式是 initializer-clause。
    •   
  2. 不,没有办法制作非模板类型安全的可变参数函数。你有什么是好的。最近有一个question about this

相关问题