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

时间:2013-11-04 09:53:48

标签: c++ templates

请考虑以下代码:

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<’

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

3 个答案:

答案 0 :(得分:2)

看起来好像你想写

t. template call<S>();

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

答案 1 :(得分:2)

你需要说

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

因为T是依赖类型名称,编译器不知道call()是模板函数,所以你必须清楚说明。

答案 2 :(得分:1)

您需要使用template关键字消除解析:

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