我正在尝试创建一个模板化 vector ,其中模板类型由运行时参数确定。我知道模板的东西在运行时之前完成,基本上我试图将运行时输入汇集到一些先前选择的编译时类型中。这是我希望能够执行的操作的高级示例。
for (int i = 0; i < 2; ++i)
{
std::vector<getRunTimeT(i)> v;
// Do stuff with v
}
因此,应该使用运行时输入选择的类型来初始化 vector 。
到目前为止,我得出的结论是需要专门的模板元编程,并且我拥有使用编译-时间参数完成我需要的功能:
template<int i>
struct getCompileTimeT
{
typedef int type; // Base case, not expected to occur.
};
template<>
struct getCompileTimeT<0>
{
typedef int type;
};
template<>
struct getCompileTimeT<1>
{
typedef float type;
};
所以我可以这样做:
std::vector<getCompileTimeT(1)> type; // Creates a vector of floats
因此,我需要以某种方式将编译时方面与一些从预定义模板类型中选择正确类型的函数联系起来。这是一个(非法)示例,说明我如何设想此桥接功能的工作方式:
// Illegal demonstrative desired functionality
_type_ getRunTimeT(int select)
{
if (select == 0) return getCompileTimeT<0>;
else if (select == 1) return getCompileTimeT<1>;
}
所以基本上我是在寻找能够在我所说的编译时功能和运行时功能之间“架起桥梁”的东西。这可能吗?
感谢您提供的任何帮助!
编辑:附加信息:
感谢您迄今为止提供的解决方案;他们在帮助我更彻底地理解这一点方面非常有用。我想提供一个 API 类型的函数,用户可以在其中操作或使用从他们的角度来看是“动态”的类型。例如:
UserClass::function()
{
for (int i = 0; i < 2; ++i)
{
// getType() is something that may be a template parameter
myFunc<getType(i)>();
}
}
template<class T>
void UserClass::myFunc()
{
std::vector<T> v;
// Now the user has a vector to play with in their member function.
}
最佳答案
试试这个
template <class T>
void do_stuff()
{
std::vector<T> v;
// Do stuff with v
}
void do_suff_dispatch(int i)
{
switch (i)
{
case 0:
do_stuff<int>();
break;
case 1:
do_stuff<float>();
break;
}
}
for (int i = 0; i < 2; ++i)
{
do_suff_dispatch(i);
}
关于C++ 模板元编程——根据运行时输入返回一个类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23484956/