c++ - 当方法可用时,我如何专门化模板?

标签 c++ templates c++17 sfinae function-templates

我想知道当我的类型具有特定方法时,我如何才能拥有专门的模板。我们以下面的代码为例:

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)而且我知道我不能部分特化一个函数调用,但是它显示了我的需要。

知道如何实现这样的目标吗?我应该使用结构进行部分特化然后使用辅助函数吗?

最佳答案

你走的很好,但是,有了转发引用,

decltype(&T::log) 变为无效的 decltype(&(Y&)::log)

使用 std::decay解决了您的问题:

template<typename T, 
    std::enable_if_t<
        std::is_member_function_pointer_v<decltype(&std::decay_t<T>::log)>,
        int> = 0>
void foo(T&& v)
{
    v.log();
}

Demo

关于c++ - 当方法可用时,我如何专门化模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68745645/

相关文章:

c++ - 专业环境中的 Qt

c++ - 针对特定接口(interface)的模板函数专门化

c++ - 具有模板化类的通用引用

c++ - std::optional:simple 和 ref-qualified value() 之间的有效区别

c++ - 如何使用 Apache C 模块记录到文件

php - 如何使用 Microsoft Visual C++ 2008 编译 PHP 扩展?

c++ - 用于 C、C++ 或 Fortran 的代码抛光器/重组器

c++ - 如何使模板化运算符推断出正确的返回类型?

c++ - CppCon 2018,尼古拉 Josuttis : Why are these interpreted as iterators?

c++ - 使用STL的简单 View