CRTP does not work / decltype

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

Seems pretty simple to me. But MSVC does not compile.

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

Despite the fact that the compiler will gladly accept the function call. The following sample compiles.

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

I have the same problem trying to use any types from a template argument.

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'

While class B clearly defines a type called "something." The compiler happily calls functions on an object such as T, T & or T *, but I cannot access any types from T.

+5
source share
3 answers

T::func . . : , , . ( ) ( valueof ).

, auto func() -> decltype(T::func()) , , .

+3

, , VS10.

  • T::func() A A T, CRTP, A T. - FixL return static_cast<T*>(this)->func();
  • , decltype, , func . decltype , - decltype(static_cast<T*>(nullptr)->func())
  • func B A - Fix: change A struct
  • VS10, , undefined class B decltype.

func ? ( , decltype, , , CRTPEX)

struct Base { 
    void func() { }
};

template<typename T, typename U> struct A {
    auto func() -> decltype(static_cast<T*>(nullptr)->func()) {
        return static_cast<U*>(this)->func();
    }
};


struct B : public A<Base, B>, public Base {
};

, g++ decltype - , ? , Microsoft. , , g++, VC10 .

template<typename T> struct A {
    auto func() -> decltype(static_cast<T*>(nullptr)->func()) {
        return static_cast<T*>(this)->func();
    }
};

struct B : public A<B> {
    void func() {}
};
+2

-, , , :

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

. , , , B A<B>, B , .

, , C++1y, auto ( decltype), gcc-4.8.2

template<typename T> struct A {
    auto func()
    //c++1y// -> decltype(static_cast<T*>(this)->func()) 
    {
        return static_cast<T*>(this)->func();
    }
};
class B : public A<B> {
    void func(){
    }
};

Compiles ( c++ -std=c++1y) and runs:

int main(){
  B b; b.func();
}

Two disclaimers: I do not know why this works. I do not know how standard this is.

0
source

All Articles