在运行时获取类型参数
Getting type parameters at runtime
>我有一个使用可变参数类型参数的类,这些参数只能在运行时用户键入输入时知道。类型参数只能是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
载体,所以它甚至看起来有些自然。
相关文章:
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 如何解决一元"*"(有"字符")错误的无效类型参数?
- C++ - 声明指向返回任何类型并获取任意数量参数的函数的指针
- "std::shared_ptr":不是参数"_Ty"的有效模板类型参数
- 具有可变参数非类型参数的模板专用化
- 函数类型参数的模板参数推导
- 当 c++ 需要一种数据类型并获取另一种数据类型时会发生什么?
- PowerShell 使用结构类型参数调用 C++ DLL 的导出函数
- 对于非常量指针类型的参数,未调用具有常量指针模板类型参数的功能
- 为模板传递非类型参数 agument
- 为什么带有类型参数的运算符 () 可以应用于 result_of 上下文中的类型?
- 使用其他模板类型参数作为要在函数签名中使用的类型别名声明
- 如何避免具有相同类型参数的函数中的错误
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- 通过命令行参数获取llvm ir文件时面临问题
- 在编译时使用可变参数模板在 c++ 中使用参数类型检查获取函数的参数数
- 从结构中获取所有可变参数模板类型,该结构是函数模板中的类型参数
- 在运行时获取类型参数
- 如何从boost::bind的类型中获取参数类型(c++11不可用)
- 从拥抱类型中获取模板参数的值