我对模板没有太多经验,但我想知道以下情况是否可能。假设我们有一个带有静态成员 stat 的类 S。我可以使用 typeid 让它动态生成不同的代码:
template <class S> void foo() { if (typeid(S::stat) == typeid(AType)) implementation 1; else implementation 2; }
但是由于所有信息在编译时都是已知的,是否有可能为 S::stat 的类型 Atype 创建 foo 的特化?
最佳答案
您可能希望做这样的事情:
template<typename T> class foo_impl {
public:
static void foo()
{
// This is your implementation 2
}
};
template<> class foo_impl<AType> {
public:
static void foo()
{
// This is your implementation 1
}
};
template <class S>
void foo()
{
foo_impl<typename S::Stat>::foo();
}
关于c++ - 基于静态成员类型的模板函数特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35761917/