>我有一个使用可变参数类型参数的类,这些参数只能在运行时用户键入输入时知道。类型参数只能是int
或string
,并且必须是 1 个或多个(这就是有 Key and
键的原因)。
using namespace std;
using Column = boost::variant<vector<int>, vector<string>>;
using Columns = vector<Column>;
namespace db {
template <typename Key, typename... Keys>
class KeyedTable {
public:
KeyedTable(const string& name);
template<typename V>
void add(const int pos, const V val, Key k1, Keys... keys);
string toString();
private:
string name;
vector<string> colNames;
map<tuple<Key, Keys...>, Columns> data;
};
}
我必须从vector<Expr>
创建此类的实例,其中每个 Expr 表示类型参数,vector
的长度表示所需的类型参数数:
class Expr {}
class IntExpr : public Expr {public: int i;}
class StringExpr : public Expr {public: string s;}
当类型参数的类型和数量仅在运行时已知时,使用此类的最佳解决方案是什么?
你要找的是不可能的。 模板在编译时解析。这意味着随后会生成所有过载。当您获得新输入时,您不能动态"添加"具有不同数量参数的新函数。(好吧,也许,从技术上讲是可能的,但它超出了标准的c ++)。
如果在运行时已知,请在运行时进行。不能将编译时逻辑与运行时逻辑混合使用。
如果您的输入有零键,您希望会发生什么?
我认为您将需要类似map<vector<KeyType>, Columns> data
.你已经有一个Columns
载体,所以它甚至看起来有些自然。