以如下代码为例:
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*));
最佳答案
&foo<int>::doit
实际上是 &foo_base<int>::doit
所以它的类型是void (foo_base<int>::*)(int*)
,但是GetType
期望类型为 void (foo<int>::*)(T*)
的参数所以不能推断T
.
关于c++ - 非依赖名称场景中模板基类的名称查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52631481/