繁体   English   中英

如何检查可变参数模板中的非原始类型?

[英]How to check for non primitive types in variadic templates?

我正在尝试编写一个名为print()的实用程序函数,其中如果传递了原始类型,则只打印它,并且如果传递了原始类型的std::vector<int> ,它必须遍历并打印。 我尝试了intstd::vector ,但失败了,主要是因为我不确定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;
}

这是我遇到的错误,如果有帮助的话:

util.cc: In instantiation of 'void print(std::ostream&, T, Args ...) [with T = const char*; Args = {int, double, std::vector<int, std::allocator<int> >}; std::ostream = std::basic_ostream<char>]':
util.cc:26:36:   required from here
util.cc:11:42: error: request for member 'begin' in 'type', which is of non-class type 'const char*'
   for (auto vector_iterator = type.begin();
                                          ^
util.cc:12:20: error: request for member 'end' in 'type', which is of non-class type 'const char*'
    vector_iterator != type.end(); ++vector_iterator) {

谢谢

如果可以编译C ++ 17,则可以使用if constexpr

if constexpr (std::is_same<T, std::vector<int>>::value)

在C ++ 17之前,您必须开发不同的函数,因为type.begin() / type.end()部分也会在value为false时(也在T不是std::vector )进行编译。

以下是“拆分”功能的一种可能方法:

template <typename... Args>
void print (std::ostream& out, std::vector<int> const & v, Args... args) 
 {
   for (auto const & i : v)
     out << i << ' ';

   print(out, args...);
 }

template <typename T, typename... Args>
void print (std::ostream& out, T type, Args... args) 
 {
   out << type;

   print(out, args...);
 }

或者,如果您想截取不同的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...);
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM