【问题标题】:template with bool parameter带有布尔参数的模板
【发布时间】:2014-07-05 20:34:52
【问题描述】:

我需要用 bool 参数实现模板。 如果 bool=true,我们需要使用列表容器,否则我们需要使用向量容器。

template <bool isList>

我该怎么做?

【问题讨论】:

  • 如 MM 所回答,使用std::conidtional 或专门针对truefalse 的模板
  • 模板函数或类型?

标签: c++ templates boolean


【解决方案1】:

您至少有三种方法可以做到这一点。

我。使用std::conditional:

template <bool isList>
struct A
{
    typename std::conditional<isList, 
                              std::list<int>,
                              std::vector<int>>::type container;
};

二。使用template specialization 作为bool 参数

template <bool isList>
struct A;

template<>
struct A<true>
{
    std::list<int> container;
};

template<>
struct A<false>
{
    std::vector<int> container;
};

然后

A<true>  a1; // container of a1 is a list
A<false> a2; // container of a2 is a vector

三。使用模板函数

如果你需要一个模板函数类型,那么你可以像下面那样做。它根据入口参数返回一个容器。

template <bool isList>
auto func() -> typename std::conditional<isList, 
                                         std::list<int>,
                                         std::vector<int>>::type
{
    typename std::result_of<decltype(func<isList>)&()>::type result;

    // ...

    return result;
};

然后

auto f1 = func<true>();  // f1 is a list
auto f2 = func<false>(); // f2 is a vector

【讨论】:

    【解决方案2】:

    从 c++17 开始,有一些更简洁的选项。

    类/结构

    对于类,我建议您与 masoud 对 std::conditional 的回答不同的是,在声明成员变量时使用 using 声明而不是直接使用类型。这样,该类型可以重复使用,typename 是多余的。此外,std::conditional_t 更短。

    例子:

    template<bool isList, typename T>
    struct TemplatedStruct
    {
        using Container = std::conditional_t<isList, std::list<T>, std::vector<T>>;
        Container container;
    };
    

    功能

    1. 使用带有if constexpr 语法的模板函数以及auto 返回类型推导。示例:
    template<bool isList, typename T>
    auto createContainer()
    {
        if constexpr (isList)
        {
            return std::list<T>{};
        }
        else
        {
            return std::vector<T>{};
        }
    }
    
    1. 使用 std::conditional 就像在 masoud 的回答中一样,但更简洁。 要么:
    template<
        bool isList, typename T, 
        typename Container = std::conditional_t<isList, std::list<T>, std::vector<T>>
    >
    auto createContainer() -> Container
    {
        Container result;
        // Do stuff that works with both containers I guess
        return result;
    }
    

    或者:

    template<bool isList, typename T>
    auto createContainer()
    {
        using Container = std::conditional_t<isList, std::list<T>, std::vector<T>>;
        Container result;
        // Do stuff that works with both containers I guess
        return result;
    }
    

    我删除了

    #include <list>
    #include <vector>
    

    为了简单起见,来自我的示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-08
      • 2016-04-16
      • 2014-06-18
      • 2011-08-25
      • 2015-05-14
      • 2014-04-12
      • 1970-01-01
      相关资源
      最近更新 更多