函数模板部分专业化-有什么解决方法吗

Function template partial specialization - are there any workaround?

本文关键字:解决 方法 什么 专业化 函数模板部      更新时间:2023-10-16

我有以下函数

enum class NodeCachingOptions
{
AddPath,
DontAddPath
};
template <typename T, NodeCachingOptions>
T* CreateSObject(const MPath& path)

想法是为不同的NodeCachingOptions专门化功能。

事实证明,使用部分函数模板专业化是不可能的,因此我尝试了一种变通方法:

template <typename T, NodeCachingOptions>
T* CreateSObject(const MPath& ob)
{
CreateSObject_Impl<class T, NodeCachingOptions> temp
return temp.call(ob);
}
template <typename T, NodeCachingOptions>
struct CreateSObject_Impl
{
T* call(const MPath& ob);
};
template <typename T>
struct CreateSObject_Impl<typename T, NodeCachingOptions::AddPath>
{
T* call(const MDagPath& ob)
{…}
}
template <typename T>
struct CreateSObject_Impl<typename T, NodeCachingOptions::DontAddPath>
{…}

然而,我得到了编译错误::NodeCachingOptions':非类型模板参数'__formal'的非法类型

我做错了什么?有没有更好的方法来解决这个问题?

我从这里得到了structimpl的想法:免费函数的部分模板专业化-最佳实践

您的语法完全错误。使其

template <typename T, NodeCachingOptions opt>
T* CreateSObject(const MPath& ob)
{
CreateSObject_Impl<T, opt> temp;
return temp.call(ob);
}

传递类型NodeCachingOptions作为CreateSObject_Impl的第二个模板参数,而不是类型本身。

您可能希望使call成为CreateSObject_Impl的静态成员,并编写return CreateSObject_Impl<T, opt>::call(ob);