如何根据类模板参数值选择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
依赖的。非常感谢您的帮助!
std::conditional_t
做出决定:
void f(std::conditional_t<plainPointer, T*, std::shared_ptr<T>> x) {
/*implementation*/
}