【发布时间】:2021-10-15 03:06:37
【问题描述】:
我想知道当我的类型有一个特定的方法时,我怎么能有一个专门的模板。我们以下面的代码为例:
template<typename T, typename... Args>
void foo(T&& arg, Args&&... args)
{
std::cout << "called 1\n";
}
template<typename T, std::enable_if_t<std::is_member_function_pointer_v<decltype(&T::log)>, int> = 0>
void foo(T&& v)
{
v.log();
}
struct Y
{
void log() const
{
std::cout << "called 2\n";
}
};
int main()
{
foo(1); // <-- print "called 1";
Y y;
foo(y); // <-- print "called 2";
}
我应该说这段代码不起作用(第二个foo 将使用主模板并打印called 1),我知道我不能部分专门化函数调用,但它显示了我需要的东西。
知道如何实现这样的目标吗?我应该使用结构来部分特化然后使用辅助函数吗?
【问题讨论】:
-
顺便说一句,你没有专门化,但提供了重载。
标签: c++ templates c++17 sfinae function-templates