c++ 如何使类模板的成员函数的参数依赖于类模板的参数值?

7qhs6swi  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(84)

如何根据类模板参数值选择类模板成员函数的参数类型?
下面是一个示例:

#include <memory>
template <class T, bool plainPointer=true>
class C
{
    // pseudocode below
    void f(plainPointer ? T * x : std::shared_ptr<T> x) { /*implementation*/ }
};

字符串
也就是说,如果plainPointer==true,则应定义以下类成员函数:

void f(T * x) { /*implementation*/ }


否则,此成员函数应定义为:

void f(std::shared_ptr<T> x) { /*implementation*/ }


我希望两个函数都有一个 * 单一的实现 *,只有f的参数类型应该是plainPointer依赖的。

nwlqm0z1

nwlqm0z11#

您可以使用std::conditional_t在两种类型之间进行选择:

void f(std::conditional_t<plainPointer, T*, std::shared_ptr<T>> x) {
   /*implementation*/ 
}

字符串
请注意,要使这种方法工作,conditional_t中的两个选项必须对所有示例化都是格式良好的。
如果您计划在类中多次使用该函数参数类型,则可以创建一个可以重用的类型别名:

using ptr_type = std::conditional_t<plainPointer, T*, std::shared_ptr<T>>;

相关问题