在类模板中调用模板成员函数时未解析的重载函数类型

Unresolved overloaded function type while calling template member function in a class template

本文关键字:函数 重载 类型 调用 成员      更新时间:2023-10-16

请考虑以下代码:

struct Test {
    template <int S>
    bool call();
};
template <>
bool Test::call<0>() {
    return false;
}
template <>
bool Test::call<1>() {
    return true;
}
template <int S, typename T>
static void func(T& t) {
    t.call<S>();
}
int main()
{
    Test t;
    func<0>(t);
}

我收到编译错误:

a.cpp: In function ‘void func(T&)’:
a.cpp:19:15: error: expected primary-expression before ‘)’ token
a.cpp: In instantiation of ‘void func(T&) [with int S = 0; T = Test]’:
a.cpp:25:14:   required from here
a.cpp:19:5: error: invalid operands of types ‘<unresolved overloaded function type>’ and ‘int’ to binary ‘operator<’

如果我在main()函数中放入t.call<0>()t.call<1>(),它可以正常工作。 有人可以告诉我为什么模板参数推断不适用于此代码吗? 我不确定为什么在这种情况下传递具有部分专用模板成员函数的类型不起作用。

你需要说

template <int S, typename T>
static void func(T& t) {
    t.template call<S>();
}

由于T是依赖类型名称,因此编译器不知道call()是模板函数,因此您必须明确说明。

您需要

使用 template 关键字消除解析的歧义:

template <int S, typename T>
static void func(T& t)
{
    t.template call<S>();
}

看起来你想写

t. template call<S>();

名称call显然是依赖的,因此,除非明确声明它是模板,否则不被视为模板。目前,我无法轻松检查这是否是唯一的问题。