I am a newbie in C++ and made a test program to learn more about decltype, std::decay, std::is_same_v(traits) and also typeid.
I have following simple class, in which I wanted to get the template parameter type Type in the Base class's constructor using decltype.
like decltype(content of std::vector<Type>::iterator::begin). Some how, it did not work.
#include <iostream>
#include <vector>
#include <type_traits>
#include <initializer_list>
#include <typeindex>
template<typename Type> class Base
{
std::vector<Type> vec;
public :
Base(std::initializer_list<decltype(*vec.begin())> liVec): vec(liVec) {}
// here ^^^^^^^^^^^^^^^^^^^^^^^^ . isn't enough??
};
int main()
{
//Base<int> obj{ 1, 2, 3, 4, 5 }; // does not works: error !
// to see the type, I wrote the following code
std::vector<int> vec;
std::cout << typeid(decltype(*vec.begin())).name() << std::endl; // prints i means int type(I know not reliable though)
// and
std::cout << std::boolalpha << std::is_same_v<int, decltype(*vec.begin())> << std::endl; // prints false
return 0;
}
The error on the line Base<int> obj{ 1, 2, 3, 4, 5 }; was(in GCC 6.1, C++14)
include\c++\initializer_list||In instantiation of 'class std::initializer_list<int&>':|
include\c++\initializer_list|54|error: forming pointer to reference type 'int&'|
include\c++\initializer_list|55|error: forming pointer to reference type 'int&'|
main.cpp|17|error: no matching function for call to 'Base<int>::Base(<brace-enclosed initializer list>)'|
candidate: 'Base<Type>::Base(std::initializer_list<decltype (*((Base<Type>*)(void)0)->Base<Type>::vec.begin())>) [with Type = int; decltype (*((Base<Type>*)(void)0)->Base<Type>::vec.begin()) = int&]'|
main.cpp|11|note: candidate expects 1 argument, 5 provided|
main.cpp|7|note: candidate: 'Base<int>::Base(const Base<int>&)'|
main.cpp|7|note: candidate expects 1 argument, 5 provided|
main.cpp|7|note: candidate: 'Base<int>::Base(Base<int>&&)'|
main.cpp|7|note: candidate expects 1 argument, 5 provided|
As I saw the compiler told me something about int&, I simply tried it with following.(i.e, std::decay_t) and it worked.
template<typename Type> class Base
{
std::vector<Type> vec;
public :
Base(std::initializer_list<std::decay_t<decltype(*vec.begin())>> liVec): vec(liVec) {}
^^^^^^^^^^^^^^^^^^^^^^^^ why I need this here?
};
int main()
{
Base<int> obj{ 1, 2, 3, 4, 5 }; // works now
std::vector<int> vec;
std::cout << typeid(decltype(*vec.begin())).name() << std::endl; // prints i means int type(not reliable though)
// and
std::cout << std::boolalpha << std::is_same_v<int, std::decay_t<decltype(*vec.begin())>> << std::endl; // true now: WHY?
return 0;
}
But I don't know the meaning of the error and why it worked. Could someone explain me what exactly happend?