首页 > 解决方案 > 在非依赖名称场景中对模板基类进行名称查找

问题描述

以下面的代码为例:

template <typename T>
struct foo_base
{
    void doit(T*) {}
};

template <typename T>
struct foo : foo_base<T> {};

template <typename T>
struct get_result
{
    template <typename Result>
    static Result GetType(void (T::*)(Result*));

    using type = decltype(GetType(&T::doit));
};

int main()
{
    std::cout << typeid(typename get_result<foo<int>>::type).name() << '\n';
}

此代码无法同时使用 GCC 和 Clang 编译,但使用 MSVC 编译成功。clang给出的错误是:

<source>:21:27: error: use of undeclared identifier 'GetType'
    using type = decltype(GetType(&T::doit));
                          ^
<source>:26:34: note: in instantiation of template class 'get_result<foo<int> >' requested here
    std::cout << typeid(typename get_result<foo<int>>::type).name() << '\n';
                                 ^
<source>:19:19: note: must qualify identifier to find this declaration in dependent base class
    static Result GetType(void (T::*)(Result*));
                  ^

通常,在一致性方面,我会支持 GCC/Clang,尤其是当它们都同意时,但我无法准确解释原因。当get_result<foo<int>>被实例化时,它也应该实例化foo_base<int>,所以我认为表达式T::doit应该编译没有问题。

FWIW 的解决方法相当简单:

template <typename Type, typename Result>
static Result GetType(void (Type::*)(Result*));

标签: c++

解决方案


&foo<int>::doit实际上是&foo_base<int>::doit

所以它的类型是void (foo_base<int>::*)(int*),但GetType期望参数类型void (foo<int>::*)(T*),所以不能推断T


推荐阅读