C++ 模板类成员函数参数依赖于类模板参数值

问题描述 投票:0回答:1

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

这是一个例子:

#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
依赖的。

非常感谢您的帮助!

c++ templates arguments compile-time
1个回答
0
投票
您可以使用

std::conditional_t

做出决定:

void f(std::conditional_t<plainPointer, T*, std::shared_ptr<T>> x) { /*implementation*/ }
    
© www.soinside.com 2019 - 2024. All rights reserved.