c++ - CRTP 失败 w/decltype

标签 c++ visual-c++ c++11 crtp decltype

template<typename T> struct A {
    auto func() -> decltype(T::func()) {
        return T::func();
    }
};
class B : public A<B> {
    void func() {
    }
};

对我来说似乎很简单。但是 MSVC 无法编译。

visual studio 2010\projects\temp\temp\main.cpp(4): error C2039: 'func' : is not a member of 'B'
visual studio 2010\projects\temp\temp\main.cpp(8) : see declaration of 'B'
visual studio 2010\projects\temp\temp\main.cpp(8) : see reference to class template instantiation 'A<T>' being compiled
          with
          [
              T=B
          ]
visual studio 2010\projects\temp\temp\main.cpp(4): error C3861: 'func': identifier not found

即使编译器会很乐意接受调用该函数。下面的示例可以正常编译。

template<typename T> struct A {
    void func() {
        return T::func();
    }
};
class B : public A<B> {
    void func() {
    }
};

我在尝试使用模板参数中的任何类型时遇到了同样的问题。

template<typename T> struct A {
    typedef typename T::something something;
};
class B : public A<B> {
    typedef char something;
};

visual studio 2010\projects\temp\temp\main.cpp(4): error C2039: 'something' : is not a member of 'B'

而 B 类明确定义了一种称为“某物”的类型。编译器非常乐意在 T、T& 或 T* 类型的对象上调用函数,但我似乎无法从 T 访问任何类型。

最佳答案

您正在尝试在声明之前使用 T::func。这就是编译器对你大喊大叫的原因。请注意,当您从类派生时,如果该类来自类模板,则会生成该类。类的隐式生成(称为隐式实例化)需要为其所有成员生成声明(因此编译器知道类的 sizeof 值,并可以对其执行查找)。

因此它还实例化声明 auto func() -> decltype(T::func()) 并且肯定会在这里失败。

关于c++ - CRTP 失败 w/decltype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4225706/

相关文章:

c++ - TCP/IP 和设计网络应用程序

c++ - 如何在 C++ 中读取 Cyrillic Unicode 文件?

c++ - x64 转换后指针截断

c++ - 具有可变参数的嵌套宏在 GCC 中编译但在 MSVC 中不编译

c++ - 从一个类到任何类的成员函数的函数指针

c++ - “ self ”不是有效目标。混合 Objective-C 和 C++ (Objective-C++)

c++ - VS2008 64 位 fread 失败

C++ 如何使用 onClick 事件创建文本框?

c++ - std::unique_ptr 用法

c++ - 如何在单独的线程中调用方法并使用返回状态