【发布时间】:2017-11-28 08:21:14
【问题描述】:
我正在尝试为我的模板类编写一个打印函数:
struct ColumnKey;
template <class Type, class Key = ColumnKey>
class Column {
protected:
std::shared_ptr<Type> doGet() {
std::lock_guard<std::mutex> lock(mutex_);
return std::make_shared<Type>(value_);
}
void doSet(const std::shared_ptr<Type> &value) {
std::lock_guard<std::mutex> lock(mutex_);
value_ = *value;
}
private:
Type value_;
std::mutex mutex_;
};
template<class... Columns>
class Table : private Columns... {
public:
template<class Type, class Key = ColumnKey>
std::shared_ptr<Type> get() {
return Column<Type, Key>::doGet();
}
template<class Type, class Key = ColumnKey>
void set(const std::shared_ptr<Type> &value) {
Column<Type, Key>::doSet(value);
}
std::string get_table_row() {
return "hello_row";
}
};
我想在Table 类中创建一个函数get_table_row,它返回columnA + "," + columnB + "," + ..
我正在尝试以这种方式编写,但出现编译错误。有人可以指出我的方法中的错误吗?
template <class Column<class Type, class Key = ColumnKey>>
std::string get_row() {
return std::to_string( *Column<Type, Key>::doGet() );
}
template <class Column<class Type, class Key = ColumnKey>, class... Columns>
std::string get_row() {
return ( std::to_string(*Column<Type, Key>::doGet()) + "," + Columns.get_row() );
}
我正在努力做到这一点,有人可以指导我吗?
【问题讨论】:
-
您可能希望递归地遍历模板参数,请参阅this answer
-
@piwi 我认为这与我想要实现的目标有些不同。我也有
Key,我想return一个值。另外,我只想打电话给Table<Column<int>, Column<std::string, Key1>, Column<std::string, Key2>>.get_row()。基本上,没有传递任何参数。 -
@piwi 可能是链接的,但我很困惑,任何帮助将不胜感激
-
您对
shared_ptr的使用对我来说似乎很复杂。你想在那里做什么?在当前的实现中,每次调用doGet最终都会将列内容复制到新分配的shared_ptr
标签: c++ variadic-templates template-meta-programming