特别是Clang 3.6.0,目前由Coliru主持.
所有这些片段都来自:
int main() {
foo();
std::cout << "\n----\n";
foo(1, 2, 3);
}
Run Code Online (Sandbox Code Playgroud)
以下代码:
template <class... Args>
void foo(Args... args) {
std::cout << ... << args;
}
Run Code Online (Sandbox Code Playgroud)
触发以下编译错误:
main.cpp:7:17: error: expected ';' after expression
std::cout << ... << args;
^
;
main.cpp:7:15: error: expected expression
std::cout << ... << args;
^
Run Code Online (Sandbox Code Playgroud)
所以我试着在表达式周围添加括号:
(std::cout << ... << args);
Run Code Online (Sandbox Code Playgroud)
它有效,但会触发警告:
main.cpp:7:6: warning: expression result unused [-Wunused-value]
(std::cout << ... << args);
^~~~~~~~~
main.cpp:11:5: note: in instantiation of function template specialization 'foo<>' …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个基于数学向量的类:
template <unsigned N> class Vector{
public:
Vector() = default;
Vector(std::initializer_list<double> li) { *this = li;}
Vector& operator=(std::initializer_list<double>);
private:
std::array<double, N> x = {}
}
template <unsigned N> inline Vector<N>& Vector<N>::operator=(std::initializer_list<double> li){
if(N != li.size()) throw std::length_error("Attempt to initialise Vector with an initializer_list of different size.");
std::copy(li.begin(), li.end(), x.begin());
return *this;
}
Run Code Online (Sandbox Code Playgroud)
我希望能够编写这样的代码;
Vector<3> a = {1,2,3};
a = {3,5,1};
Run Code Online (Sandbox Code Playgroud)
用户期望编写这样的代码是很自然的,对吧?但是,如果我使用错误大小的初始化列表,我希望发生编译时错误std::array.
std::array<double, 3> a = {2,4,2,4} //compile time error
Vector<3> a = {3,5,1,5} //run-time error as …Run Code Online (Sandbox Code Playgroud) 在学习模板参数包时,我正在尝试编写一个聪明,简单的函数来有效地将两个或多个std::vector容器附加到一起.
以下是两个初始解决方案.
版本1优雅但有缺陷,因为它在参数包的扩展期间依赖于副作用,并且评估的顺序是未定义的.
版本2有效,但依赖于需要两种情况的辅助函数.呸.
你能看出你是否能想出一个更简单的解决方案吗?(为了提高效率,不应多次复制矢量数据.)
#include <vector>
#include <iostream>
// Append all elements of v2 to the end of v1.
template<typename T>
void append_to_vector(std::vector<T>& v1, const std::vector<T>& v2) {
for (auto& e : v2) v1.push_back(e);
}
// Expand a template parameter pack for side effects.
template<typename... A> void ignore_all(const A&...) { }
// Version 1: Concatenate two or more std::vector<> containers into one.
// Nicely simple, but buggy as the order of evaluation is undefined.
template<typename T, typename... …Run Code Online (Sandbox Code Playgroud)