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?
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.
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.
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.
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.
*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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With