Pattern Programming - Common Mistakes

Possible duplicate:
C ++ template gotchas

Hi,

I am in my second month on SO, and I have seen enough posts on SO related to several common template problems. Is it a good idea to make a little Wiki on this (unfortunately, I don't know how to do this)?

The idea is to provide the link as final as this (favorite GMan)

Here is the first one

http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12

If one already exists or this idea is not attractive, please feel free to vote for a close. I will also vote for him :)

+3
source share
3 answers

Overview of typename

The keyword typenamehas two meanings in C ++. typenamecan be used as a replacement for classin the template parameter lists.

// These two lines mean exactly the same thing.
template<typename A> class Foo {};
template<class A> class Foo {};

Another reason is more complicated. typenametells the compiler that the dependent name is actually a type.

Consider:

template<typename T>
struct Bar
{
    typedef T MyType; // Okay.
    typedef T::Type OtherType; // Wrong.
};

, , T::Type , typedef . T Type , (, ), T::Type -, , T, . T::Type - , standardese . , T , , T ( ), typename.

:

template<typename T>
struct Bar
{
    typedef T MyType; // Okay.
    typedef typename T::Type OtherType; // Okay.
};

, - typename , !

+1

.

-.

struct F {
    typedef int value_type;
};

struct B : F {
    B::value_type value;          // some compilers, edg
    typename B::value_type value;  // other compilers, gcc
    BOOST_DEDUCED_TYPENAME B::value_type value;  // Boost!!!
};

, nvcc cuda- , edg gcc, , . , , BOOST_DEDUCED_TYPENAME .: - (

+1

struct base{
    virtual void f(){}
};

template<class T> struct anotherbase{
    virtual void f(){}
};

template<class T> struct derived : base, anotherbase<T>{
    void g(){f();}
};

int main(){
    derived<int> d;
    d.g();             // not ambiguous. should call base::f
                        // unqualified name 'f' is not looked up 
                        // anotherbase<int>
}
0

Source: https://habr.com/ru/post/1765930/


All Articles