我遇到一种情况,我需要传递可变数量的整数(在编译时已知)。
我需要实现这样的目标:
template <unsigned N>
void myFunc(std::array<int, N> values)
{
// Do something useful with the values
}
Run Code Online (Sandbox Code Playgroud)
我希望上面的代码能够工作,并且可以像这样方便地调用,而无需创建临时对象;
myFunc<4>({1, 2, 3, 4});
这实际上确实有效,但问题是这也有效......
myFunc<4>({1, 2});
这当然会使其中两个值未初始化,而我和用户都不知道。
我相信这会起作用:
template <unsigned N>
void myFunc(std::vector<int> values)
{
assert(values.size() == N);
// Do something useful with the values
}
Run Code Online (Sandbox Code Playgroud)
myFunc<4>({1, 2}); // Goes bang
myFunc<4>({1, 2, 3, 4}); // OK
Run Code Online (Sandbox Code Playgroud)
不幸的是,我无法在我的环境中分配内存),所以我必须在堆栈上执行所有操作(并且不能只接受我可以检查其大小的向量)。
我认为自己有两个选择。
我正在编写一个对象分配器,我想通过以下方式调用它:
T result = factoryObject.construct(argA, argB, argC);
Run Code Online (Sandbox Code Playgroud)
我目前有这个设计,它有效......
class Factory {
void* memPool_;
template <typename Tret, typename... Args>
Tret construct(Args&&... args) {
Tret::methodA(std::forward<Args&&>(args));
Tret::Tret(memPool_, std::forward<Args&&>(args);
}
}
Run Code Online (Sandbox Code Playgroud)
...只要我用以下方式调用它:
T result = factoryObject.construct<T>(argA, argB, argC);
Run Code Online (Sandbox Code Playgroud)
我希望能够在不明确指定的情况下做到这一点T。T可能会变得非常复杂,我需要在初始化列表中使用这个工厂内联。我还需要在构造函数初始化列表中使用它,所以我无法调用auto result = factory.construct<T>()(我只需要它根据它正在构造的内容推断返回类型)。
我尝试使用operator()技巧推断类型(根据/sf/answers/182910731/):
public:
template <class T>
operator T() { return T(); }
};
class GC {
public:
static Allocator Allocate() { return Allocator(); }
};
int main() {
int p = GC::Allocate();
}
Run Code Online (Sandbox Code Playgroud)
...但这不允许我传递参数(因为 operator() …