模板与bool参数

use*_*224 15 c++ templates boolean

我需要用bool参数实现模板.如果bool = true,我们需要使用list conteiner,否则我们需要使用vector conteiner.

template <bool isList>
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

mas*_*oud 30

使用std::conditional模板专业化.

一世.结构/班

template <bool isList>
struct A
{
    typename std::conditional<isList, 
                              std::list<int>,
                              std::vector<int>>::type container;
};
Run Code Online (Sandbox Code Playgroud)

或者,您可以专门化bool参数的模板

template <bool isList>
struct A;

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

template<>
struct A<false>
{
    std::vector<int> container;
};
Run Code Online (Sandbox Code Playgroud)

然后

A<true>  a1; // container of a1 is a list
A<false> a2; // container of a2 is a vector
Run Code Online (Sandbox Code Playgroud)

 

II.模板功能

如果您需要模板功能类型,那么您可以像下面这样做.它根据entry参数返回一个容器.

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;
};
Run Code Online (Sandbox Code Playgroud)

然后

auto f1 = func<true>();  // f1 is a list
auto f2 = func<false>(); // f2 is a vector
Run Code Online (Sandbox Code Playgroud)


Bjö*_*din 5

从 c++17 开始,有一些更干净的选择。

类/结构

对于类,我唯一​​建议您与 masoud 的答案不同的std::conditionalusing在声明成员变量时使用声明而不是直接使用类型。这样,类型可以重用并且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;
};
Run Code Online (Sandbox Code Playgroud)

职能

  1. 使用带有if constexpr语法和auto返回类型推导的模板化函数。例子:
template<bool isList, typename T>
auto createContainer()
{
    if constexpr (isList)
    {
        return std::list<T>{};
    }
    else
    {
        return std::vector<T>{};
    }
}
Run Code Online (Sandbox Code Playgroud)
  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;
}
Run Code Online (Sandbox Code Playgroud)

或者:

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;
}
Run Code Online (Sandbox Code Playgroud)

我删除了

#include <list>
#include <vector>
Run Code Online (Sandbox Code Playgroud)

为了简单起见,从我的例子中。