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)。我想问以下问题:
我不太喜欢 all_true 的声明,因为我知道类型但我使用模板。是否可以使用类似于以下内容的内容?
constexpr bool all_true(bool head, bool... tail){...} // This code doesn't compile
Run Code Online (Sandbox Code Playgroud)谢谢!
| 归档时间: |
|
| 查看次数: |
1066 次 |
| 最近记录: |