可变参数类中的模板函数

template function within variadic class

本文关键字:函数 变参 参数      更新时间:2023-10-16

为什么goo中的注释行无法编译?相反,我必须求助于定义全局函数hoo而不是使用 Thing 成员函数foo

#include <iostream>
template <typename... T>
struct Thing {
    template <typename U> void foo() {std::cout << this << 'n';}
};
template <typename U, typename... T>
void hoo (const Thing<T...>& thing) {std::cout << &thing << 'n';}
template <typename U, typename... T>
void goo (const Thing<T...>& thing) {
//  thing.foo<U>();  // Why won't this line compile?
    hoo<U>(thing);  // Using this instead.
}
int main() {
    Thing<int, double, char> thing;
    goo<short>(thing);
}

需要什么更改才能改用 foo((?

thing.foo<U>()编译器没有足够的信息来判断foo是否是模板。 使用 template 关键字消除歧义:

thing.template foo<U>();