为什么在以下情况下需要使用std :: decay?

时间:2018-09-16 09:37:51

标签: c++ templates c++14

我是C ++的新手,并且制作了一个测试程序,以详细了解decltypestd::decaystd::is_same_v(特征)以及typeid

我有一个简单的类,其中我想使用TypeBase类的构造函数中获取模板参数类型decltype

类似于decltype(content of std::vector<Type>::iterator::begin)。一些如何,它没有用。

#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;
}

Base<int> obj{ 1, 2, 3, 4, 5 };行上的错误是(在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|

当我看到编译器告诉我有关int&的一些信息时,我只是通过以下方法(即std::decay_t)对其进行了尝试,并且可以正常工作。

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;
}

但是我不知道该错误的含义以及它为什么起作用。有人可以解释我到底发生了什么吗?

1 个答案:

答案 0 :(得分:2)

错误消息的第一行显示(除其他外):

instantiation of 'class std::initializer_list<int&>'

因此,它试图创建具有引用类型 initializer_list

查看您的模板代码:

 std::initializer_list<decltype(*vec.begin())>

现在vec.begin()产生 iterator ,而取消引用 iterator 产生 reference ,因此您可以执行以下操作:

*iter = whatever;

因此,您需要删除该类型的 reference 部分。 std::decay_t做到了。