Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template function is_same in template classes

Why this code produces a false output?

//this-type.cpp  

#include <iostream>
#include <type_traits>

using namespace std;

template<typename testype>
class A
{
public:
    A()
    {
        cout << boolalpha;
        cout << is_same<decltype(*this), A<int>>::value << endl;
    }
};

class B : public A<int>
{
};

int main()
{
    B b;
}

Output:

$ g++ -std=c++11 this-type.cpp
$ ./a.out
false

The type of "*this" inside A through B is A< int >, isn't it?

like image 710
Peregring-lk Avatar asked Dec 12 '12 15:12

Peregring-lk


People also ask

What is the difference between template class and template function?

For normal code, you would use a class template when you want to create a class that is parameterised by a type, and a function template when you want to create a function that can operate on many different types.

What is std :: Is_same?

struct is_same; (since C++11) If T and U name the same type (taking into account const/volatile qualifications), provides the member constant value equal to true.

Which function is useful when template of template is used?

Explanation: As a template feature allows you to write generic programs. therefore a template function works with any type of data whereas normal function works with the specific types mentioned while writing a program.

What is the need of function templates and class templates explain?

It allows you to define the generic classes and generic functions and thus provides support for generic programming. Generic programming is a technique where generic types are used as parameters in algorithms so that they can work for a variety of data types. Templates can be represented in two ways: Function templates.


2 Answers

*this is an lvalue of type A, so decltype(*this) will give the reference type A &. Recall that decltype on an lvalue gives the reference type:

    cout << is_same<decltype(*this), A<int>>::value << endl;
    cout << is_same<decltype(*this), A<int> &>::value << endl;

Output:

false
true
like image 58
ecatmur Avatar answered Oct 01 '22 13:10

ecatmur


Try:

typedef std::remove_reference<decltype(*this)>::type this_type;
cout << is_same<this_type, A<int>>::value << endl;

and maybe remove_cv in some other contexts (if you don't care about const/volatile) like this:

typedef std::remove_reference<decltype(*this)>::type this_type;
typedef std::remove_cv<this_type>::type no_cv_this_type;
cout << is_same<no_cv_this_type, A<int>>::value << endl;
like image 35
Yakk - Adam Nevraumont Avatar answered Oct 01 '22 12:10

Yakk - Adam Nevraumont