c++ - 为在 vector 中调用模板初始化的模板类创建构造函数

标签 c++ templates c++11 stdvector

如果我想创建一个能够调用模板构造函数的模板类(在类构造函数中),是否可以这样做?或者有更好的解决方案吗?

template<typename T>
class A{
public:
    A(int n): mVector(n) {}                //normal constructor
    A(int n, auto a): mVector(n, T(a)) {}  //constructor with template initialization
private:
    std::vector<T> mVector;
};

还有没有一种方法可以针对任意数量的参数 T(a,b,c,...) 进行扩展,而无需为每种情况都提供构造函数?

最佳答案

也许您正在搜索这个:

template <typename... Args>
A(int n, Args&&... args) : // First argument should probably be std::size_t
    mVector(n, T(std::forward<Args>(args)...)) {}

但是,您可以只使用 const T& 并期望调用者给您一个。

关于c++ - 为在 vector 中调用模板初始化的模板类创建构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27531130/

相关文章:

c++ - 如何在大型项目中使用 -fsplit-stack

c++ - 为什么 valarray 分配不根据文档调整受让人的大小?

c++ - 调用了错误的重载模板函数

c++ - 错误 : unitialized member with const type c++

c++ - VS2013 : STL regex class crashes when regular expression contains\

c++ - 缺少用户定义的to_string()的编译时检测

c++ - 为什么 void setOutputFormat(ostream out, int decimal_places) 会导致错误?

c++ - 声明变量时逗号分隔的作用

c++ - XBee PRO S1 总是通过 API MODEM_STATUS_RESPONSE 获得响应而不是什么都没有

跨 DLL 的 C++ 成员函数显式模板实例化