如何根据类模板参数值选择类模板成员函数的参数类型?
下面是一个示例:
#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
依赖的。
1条答案
按热度按时间nwlqm0z11#
您可以使用
std::conditional_t
在两种类型之间进行选择:字符串
请注意,要使这种方法工作,
conditional_t
中的两个选项必须对所有示例化都是格式良好的。如果您计划在类中多次使用该函数参数类型,则可以创建一个可以重用的类型别名:
型