Is vector<auto> not allowed ? (error: invalid use of ‘auto’)
Is vector<auto> not allowed ? (error: invalid use of ‘auto’)
我有:
#include <cstdlib>
#include <vector>
using namespace std;
int main()
{
auto a = -SOME_CONST_MAX;
vector<auto> myVec {a, a, a, a};
}
我不知道 SOME_CONST_MAX
的类型,但我想制作一个 -SOME_CONST_MAX
类型的向量。我假设 vector<auto>
会起作用,因为它会从 a
的类型推断出来。
我收到这些错误 运行:
g++ -std=c++14 main.cpp
main.cpp:9:9: error: invalid use of ‘auto’
vector<auto> myVec {a, a, a, a};
^
main.cpp:9:13: error: template argument 1 is invalid
vector<auto> myVec {a, a, a, a};
^
main.cpp:9:13: error: template argument 2 is invalid
main.cpp:9:32: error: scalar object ‘myVec’ requires one element in initializer
vector<auto> myVec {a, a, a, a};
^
难道vector<auto>
不允许吗?我做错了什么?
我觉得 Slava 的解决方案非常简单优雅
vector<decltype(a)> myVec {a, a, a, a};
但为了展示另一种方式,您可以使用 variadic
模板函数
template <typename T, typename ... Ts>
std::vector<T> getVect (T const & t, Ts const & ... ts)
{ return { t, ts... } ; }
您可以再次使用auto
auto myVec = getVect(a, a, a, a, a);
如果我没记错的话,已经为 vector<auto>
语法提出了建议。它们未被 C++ 标准委员会接受。
C++17 将引入类似 std::vector bob = {a,a,a,a};
的东西。注意缺少 <auto>
。这可能只是语言功能,在后面的 std
中实际使用。
auto
也被添加到模板中,但是 auto
始终是一个值 从来不是一个类型。所以使用 auto
来替换类型被认为是一个坏主意。
这里是 auto
在模板中的用法:
template<auto x>
using constant_t=std::integral_constant<decltype(x),x>;
template<auto x>
constexpr constant_t<x> constant{};
现在 constant<7>
是 std::integral_constant<int,7>
。由于许多原因,这被认为是有用的。
使用当前 C++ 的实际问题的答案是:
auto a = -SOME_CONST_MAX;
std::vector<decltype(a)> myVec {a, a, a, a};
我们推断 a
的类型并将其传递给 vector
.
我有:
#include <cstdlib>
#include <vector>
using namespace std;
int main()
{
auto a = -SOME_CONST_MAX;
vector<auto> myVec {a, a, a, a};
}
我不知道 SOME_CONST_MAX
的类型,但我想制作一个 -SOME_CONST_MAX
类型的向量。我假设 vector<auto>
会起作用,因为它会从 a
的类型推断出来。
我收到这些错误 运行:
g++ -std=c++14 main.cpp
main.cpp:9:9: error: invalid use of ‘auto’
vector<auto> myVec {a, a, a, a};
^
main.cpp:9:13: error: template argument 1 is invalid
vector<auto> myVec {a, a, a, a};
^
main.cpp:9:13: error: template argument 2 is invalid
main.cpp:9:32: error: scalar object ‘myVec’ requires one element in initializer
vector<auto> myVec {a, a, a, a};
^
难道vector<auto>
不允许吗?我做错了什么?
我觉得 Slava 的解决方案非常简单优雅
vector<decltype(a)> myVec {a, a, a, a};
但为了展示另一种方式,您可以使用 variadic
模板函数
template <typename T, typename ... Ts>
std::vector<T> getVect (T const & t, Ts const & ... ts)
{ return { t, ts... } ; }
您可以再次使用auto
auto myVec = getVect(a, a, a, a, a);
如果我没记错的话,已经为 vector<auto>
语法提出了建议。它们未被 C++ 标准委员会接受。
C++17 将引入类似 std::vector bob = {a,a,a,a};
的东西。注意缺少 <auto>
。这可能只是语言功能,在后面的 std
中实际使用。
auto
也被添加到模板中,但是 auto
始终是一个值 从来不是一个类型。所以使用 auto
来替换类型被认为是一个坏主意。
这里是 auto
在模板中的用法:
template<auto x>
using constant_t=std::integral_constant<decltype(x),x>;
template<auto x>
constexpr constant_t<x> constant{};
现在 constant<7>
是 std::integral_constant<int,7>
。由于许多原因,这被认为是有用的。
使用当前 C++ 的实际问题的答案是:
auto a = -SOME_CONST_MAX;
std::vector<decltype(a)> myVec {a, a, a, a};
我们推断 a
的类型并将其传递给 vector
.