dimanche 6 août 2017

error: ... conflicts with a previous declaration

I intend to have a class which has an inner class and a method with similar names. The code of example1.cpp compiles with no problem even though I have the an inner class and a method with the same name B. While example2.cpp will not work if I rename Position to position with small letters. In such a case, the position() method and the position class conflict with each other and I receive:

error: ‘ObjType::position<false> ObjType::position() const’ conflicts with a previous declaration
  inline auto position() const->class position<false>{return {*this};}
                                                                     ^
compilation terminated due to -Wfatal-errors.

What is the difference between these two classes? Why the latter one is giving error but not the former one?

g++ -std=c++11 test2.cpp -Wall -Wextra -Wfatal-errors && ./a.out

.

// example1.cpp

#include <iostream>

class A
{
public:
    friend class B;

    class B
    {
    public:
        int x;
        void show() {std::cout<<"x: "<<x<<std::endl;}
        B(): x(6) {}
    };

    B B()
    {
        class B b;
        return b;
    }
};

int main()
{
    A a;
    a.B().show();
    return 0;
}

.

// example2.cpp

#include <iostream>

#include <iostream>
#include <iostream>
#include <type_traits>

class Point
{
public:
    double x,y,z;
    void print() const
    {
        std::cout<<"x:"<<x<<", y:"<<y<<"z:"<<z<<std::endl;
    }
};

class ObjType
{
    template<bool> friend class Position;

    Point data;
public:
    template<bool ByRef>
    class Position
    {
        typename std::conditional<ByRef,ObjType&,ObjType const&>::type ref;
    public:
        inline Position(typename std::conditional<ByRef, ObjType&, ObjType const&>::type ref) : ref(ref) {}
        inline Position(const Point &ref): ref(ref){}
        inline auto operator =(Point const& a)->Position&{ref.data.subvec(0,2)=a; return *this;}
        inline auto operator =(Point&& a)->Position&{data=a; return *this;}
        inline void print() const{ref.data.print();}
    };

    inline ObjType(const Point &data): data(data){}
    inline void print() const{data.print();}
    /*error > */ inline auto position() const->class Position<false>{return {*this};}
    inline auto position()->class Position<true>{return {*this};}
};

int main()
{
    ObjType obj({1.1,1.2,1.3});
    std::cout<<"****************"<<std::endl;
    std::cout<<"obj.print() :"<<std::endl;
    obj.print();
    std::cout<<"obj.position.print() :"<<std::endl;
    obj.position().print();
    std::cout<<"****************"<<std::endl;
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire