我有一个vec<T>常量长度等于 3 的数学向量模板类。它看起来像这样:
template <typename T>
class vec{
public:
vec() { /**/ }
vec(std::initializer_list<T> list) { /**/ }
private:
std::array<T, 3> data;
};
Run Code Online (Sandbox Code Playgroud)
我知道,可以std::array用std::initializer_list这样的方式初始化:
std::array<int, 3> a = {1, 2, 3};
Run Code Online (Sandbox Code Playgroud)
所以我想有一个构造函数std::initializer_list来初始化我的向量,如下所示:
vec<int> v = {1, 2, 3};
Run Code Online (Sandbox Code Playgroud)
我也有一个解决方案:只需遍历std::initializer_list元素并写入data:
vec(std::initializer_list<T> list) {
size_t i = 0;
for (auto it = list.begin(); it != list.end(); it++) {
data[i++] = *it;
}
}
Run Code Online (Sandbox Code Playgroud)
我试图让构造函数看起来像这样(因为std::array有一个带有 的构造函数std::initializer_list):
vec(std::initializer_list<T> …Run Code Online (Sandbox Code Playgroud) 我有两个结构,其方法在它们拥有的对象集合的开始和结束时返回迭代器。方法有不同的名称(这似乎是一个糟糕的应用程序架构,但这只是一个简化的模型):
struct A {
std::vector<int>::iterator a_begin() { return v.begin(); }
std::vector<int>::iterator a_end() { return v.end(); }
std::vector<int> v = { 1, 2 };
};
struct B {
std::vector<float>::iterator b_begin() { return v.begin(); }
std::vector<float>::iterator b_end() { return v.end(); }
std::vector<float> v = { 1.0f, 2.0f };
};
Run Code Online (Sandbox Code Playgroud)
我想编写一个模板函数,它将迭代给定的对象(类型 A 或类型 B)并对其元素做一些工作。我的做法是:
template<class T>
void foo(T t) {
if constexpr (std::is_same_v<T, A>) {
for (auto it = t.a_begin(); it != t.a_end(); it++) {
// a lot of stuff
}
} else …Run Code Online (Sandbox Code Playgroud)