C++ 如何检查可变模板中的非基本类型?
我正在尝试编写一个名为C++ 如何检查可变模板中的非基本类型?,c++,c++11,templates,variadic-templates,stdvector,C++,C++11,Templates,Variadic Templates,Stdvector,我正在尝试编写一个名为print()的实用函数,在该函数中,如果传递了一个基元类型,它将只打印它,如果传递了基元类型的std::vector,它必须循环并打印它。我尝试了 STD::vector int >代码>但是失败得很惨,主要是因为我不确定C++中是否允许这样做。如果您能提供一些通用的方法来处理所有基元类型的向量,这将非常有用 #include <iostream> #include <vector> #include <type_traits>
print()
的实用函数,在该函数中,如果传递了一个基元类型,它将只打印它,如果传递了基元类型的std::vector
,它必须循环并打印它。我尝试了<代码> STD::vector <代码> int >代码>但是失败得很惨,主要是因为我不确定C++中是否允许这样做。如果您能提供一些通用的方法来处理所有基元类型的向量,这将非常有用
#include <iostream>
#include <vector>
#include <type_traits>
void print(std::ostream& out) {}
template <typename T, typename... Args>
void print(std::ostream& out, T type, Args... args)
{
if (std::is_same<T, std::vector<int>>::value) {
for (auto vector_iterator = type.begin();
vector_iterator != type.end(); ++vector_iterator) {
out << (*vector_iterator) << " ";
}
} else {
out << type;
}
print(out, args...);
}
int main()
{
std::vector<int> v {4,5,6};
print(std::cout, "bla", 1, 23.0, v);
return 0;
}
#包括
#包括
#包括
无效打印(std::ostream&out){}
样板
无效打印(std::ostream&out、T类型、参数…参数)
{
if(std::is_same::value){
for(auto vector_iterator=type.begin();
vector_迭代器!=type.end();++vector_迭代器){
out如果可以编译C++17,那么可以使用If constexpr
if constexpr (std::is_same<T, std::vector<int>>::value)
或者,如果您想要截取不同的std::vector
类型,您可以模板化std::vector
的类型T
,并将第一个函数变为
template <typename T, typename... Args>
void print (std::ostream& out, std::vector<T> const & v, Args... args)
{
for (auto const & i : v)
out << i << ' ';
print(out, args...);
}
模板
无效打印(std::ostream&out、std::vector const&v、Args…Args)
{
用于(自动常数和i:v)
out如果可以编译C++17,那么可以使用If constexpr
if constexpr (std::is_same<T, std::vector<int>>::value)
或者,如果您想要截取不同的std::vector
类型,您可以模板化std::vector
的类型T
,并将第一个函数变为
template <typename T, typename... Args>
void print (std::ostream& out, std::vector<T> const & v, Args... args)
{
for (auto const & i : v)
out << i << ' ';
print(out, args...);
}
模板
无效打印(std::ostream&out、std::vector const&v、Args…Args)
{
用于(自动常数和i:v)
这是如果constepr
的用途。另外,如果constepr
用于循环,则使用基于范围。另外,如果constepr
用于循环,则使用基于范围。请解释为什么键入.begin()
和键入.end()
part仍在编译。如果不匹配,它不应该返回false
并转到其他部分吗?@invincible不朽-我认为您应该搜索“c++if constexpr”要了解更多信息,无论如何,关键是——在C++17if constexpr
之前——在一个函数中,所有代码都被编译;而且当部分代码从未被使用时。因此,您不能在一个函数中编写type.begin()
,因为type.begin()如果type
是int
时从未执行该行代码,则也必须编译该行代码。如果constexpr
,您希望的是。请解释一下type.begin()和type.end()的原因
part仍在编译。如果不匹配,它不应该返回false
并转到其他部分吗?@invincible不朽-我认为您应该搜索“c++if constexpr”要了解更多信息,无论如何,关键是——在C++17if constexpr
之前——在一个函数中,所有代码都被编译;而且当部分代码从未被使用时。因此,您不能在一个函数中编写type.begin()
,因为type.begin()如果type
是int
时从未执行该行代码,则也必须编译该行代码。如果constexpr
,您期望的是。