【发布时间】:2014-07-05 20:34:52
【问题描述】:
我需要用 bool 参数实现模板。 如果 bool=true,我们需要使用列表容器,否则我们需要使用向量容器。
template <bool isList>
我该怎么做?
【问题讨论】:
-
如 MM 所回答,使用
std::conidtional或专门针对true和false的模板 -
模板函数或类型?
我需要用 bool 参数实现模板。 如果 bool=true,我们需要使用列表容器,否则我们需要使用向量容器。
template <bool isList>
我该怎么做?
【问题讨论】:
std::conidtional 或专门针对true 和false 的模板
您至少有三种方法可以做到这一点。
template <bool isList>
struct A
{
typename std::conditional<isList,
std::list<int>,
std::vector<int>>::type container;
};
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
【讨论】:
从 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;
};
if constexpr 语法的模板函数以及auto 返回类型推导。示例:template<bool isList, typename T>
auto createContainer()
{
if constexpr (isList)
{
return std::list<T>{};
}
else
{
return std::vector<T>{};
}
}
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>
为了简单起见,来自我的示例。
【讨论】: