是否有方法获取模板实例的模板?
我做过这件事
#include <iostream>
using namespace std;
//some template class
template <class T>
struct Hola {
template<class H> using Base = Hola<H>; //typedef of the self template
T val;
};
int main() {
auto h = Hola<int>{}; //using template with int
h.val = 6.6;
auto b = typename decltype(h)::Base<float>{}; //using the same template with float
b.val = 6.6;
cout << h.val << endl << b.val << endl;
}它的工作就像预期的那样。
但是,我想知道,在不定义基本模板中的using子句的情况下,是否也可以这样做。我的意思是如下所示
#include <iostream>
using namespace std;
//same class without typedef of self
template <class T>
struct Hola {
T val;
};
int main() {
auto h = Hola<int>{};
h.val = 6.6;
using Templ = decltempl(h); //get the template of h
auto b = Templ<float>{}; //use the template of h with float
b.val = 6.6;
cout << h.val << endl << b.val << endl;
}注意到
假设所需类型只有一个可能的源模板,以避免部分专门化的问题。
发布于 2015-12-12 21:59:02
您可以通过部分专门化来完成这一任务。
template<typename T, typename U> struct templ_of;
template<typename T, template<typename> class U, typename A> struct templ_of<T, U<A>> {
using type = U<T>;
}
template<typename T, typename U>
using rebind = typename templ_of<T, U>::type;这台机器用于标准分配器,这些分配器是由集装箱回弹的。
发布于 2015-12-12 21:09:35
不幸的是,C++中无法存在解密说明符。这是因为模板的工作方式与其工作方式相同;-)
类模板就像蛋糕配方。当comiler注意到(在代码中)您想要使用特定种类的蛋糕(模板实例化)时,它会为您烘焙一个蛋糕(创建一个常规类,不记得它是一个模板),这样您就可以将它用作蛋糕(类),而不是菜谱(模板)。
您可以在编译时处理模板(阅读有关模板元编程的内容),但这在运行时是不可能的。
https://stackoverflow.com/questions/34242359
复制相似问题