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

S.V*_*S.V 6 c++ templates arguments compile-time

如何根据类模板参数值选择类模板成员函数的参数类型?

这是一个例子:

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

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

void f(T * x) { /*implementation*/ }
Run Code Online (Sandbox Code Playgroud)

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

void f(std::shared_ptr<T> x) { /*implementation*/ }
Run Code Online (Sandbox Code Playgroud)

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

cig*_*ien 8

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

void f(std::conditional_t<plainPointer, T*, std::shared_ptr<T>> x) {
   /*implementation*/ 
}
Run Code Online (Sandbox Code Playgroud)

请注意,要使此方法发挥作用, 中的两个选项conditional_t对于所有实例化都必须格式正确。


如果您计划在类中多次使用该函数参数类型,则可以创建一个可以重用的类型别名:

using ptr_type = std::conditional_t<plainPointer, T*, std::shared_ptr<T>>;
Run Code Online (Sandbox Code Playgroud)