【发布时间】:2018-01-25 17:57:44
【问题描述】:
我正在处理一个类模板,其中模板本身不是可变参数类型,但是类的构造函数是。我正在尝试获取参数包的所有值并将它们存储到一个向量中,但我似乎无法编译代码,我不断收到编译器错误消息,指出必须在此上下文中扩展参数包,并且我不确定正确的语法是什么。这是我的课:
template<class T>
class TableRow {
private:
std::string id_;
std::vector<T> values_;
public:
template<class T, class... Params>
TableRow( const std::string& id, T firstVal, Params... valuePack ) :
id_(id) {
values.push_back( firstVal );
for ( auto t : (valuePack...) ) { // Compiler error here
values_.push_back( t );
}
}
// ... other methods
};
除了让它正确编译之外,我唯一关心的其他问题是有没有办法确保所有Params 都是T 类型?
换句话说,这就是我在实例化这个类时想要实现的目标
TableRow<int> trInt1( "Row1", 1, 2, 3, 4, 5 );
TableRow<int> trInt2( "Row2", 6, 7, 8, 9, 10 );
TableRow<float> trFloat1( "Row1", 2.2f, 3.3f, 4.4f );
TableRow<float> trFloat2( "Row1", 4.5f, 7.9f );
// In the above examples the first two rows are of the same length
// meaning their vector sizes are equal in length therefor they are
// compatible to fit inside of single table. The table is
// a class template that takes type <T> the same type as the RowTable<T>.
// The Table<T>'s constructor accepts a TableRow<T>.
// With the next two examples of the floats they are both indeed table rows
// but they can not fit into the same table since they are of different length
// The following is what I do not want:
TableRow<char> row( "row1", 'a', 3, 5, 2.4f, someClass );
// This is not allowed, all data types from the 2nd parameter on
// must all be of the same type!
编辑
我接受了liliscent 的建议并将我的类模板的声明更改为如下所示:
template<class T>
class TableRow {
private:
std::string id_;
std::vector<T> values_;
public:
template<class... Params>
TableRow( std::string id, Params&&... valuePack ) :
id_( id ),
values_ { std::forward<Params>( valuePack )... }
{}
std::string getID() const {
return id_;
}
std::vector<T> getValues() const {
return values_;
}
std::size_t getSize() const {
return values_.size();
}
};
现在编译...感谢您的帮助,因为我现在可以继续编写本课程的其余部分。晚些时候;一旦我的两个班级一起工作,如果一切顺利,我会接受他们的回答。
【问题讨论】:
-
std::vector<T> getValues() const应该是const std::vector<T>& getValues() const以避免不必要的复制。
标签: c++ templates variadic-functions