C++ 带bool参数的模板
我需要实现带有bool参数的模板。 如果bool=true,我们需要使用列表容器,否则我们需要使用向量容器C++ 带bool参数的模板,c++,templates,boolean,C++,Templates,Boolean,我需要实现带有bool参数的模板。 如果bool=true,我们需要使用列表容器,否则我们需要使用向量容器 template <bool isList> 模板 我怎么做?你至少有三种方法 我使用: 然后 a1;//a1的容器是一个列表 A a2;//a2的容器是一个向量 三、使用模板功能 如果您需要一个模板函数类型,那么您可以像下面这样做。它根据entry参数返回一个容器 template <bool isList> auto func() -> typena
template <bool isList>
模板
我怎么做?你至少有三种方法 我使用: 然后
a1;//a1的容器是一个列表
A a2;//a2的容器是一个向量
三、使用模板功能
如果您需要一个模板函数类型,那么您可以像下面这样做。它根据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;
};
模板
auto func()->typename std::conditional::type
{
typename std::result\u of::type result;
// ...
返回结果;
};
然后
auto f1=func();//f1是一个列表
自动f2=func();//f2是一个向量
对于c++17以后的版本,有一些更干净的选项
类/结构
对于类,我建议您与masoud关于std::conditional
的回答不同的唯一一件事是在声明成员变量时使用using
声明,而不是直接使用类型。这样,该类型可以重复使用,typename
是冗余的。而且,std::conditional\u t
更短
例如:
模板
结构模板结构
{
使用Container=std::conditional\u t;
集装箱;
};
功能
if constexpr
语法的模板函数以及auto
返回类型推断。例如:模板
自动创建容器()
{
if constexpr(isList)
{
返回std::list{};
}
其他的
{
返回std::vector{};
}
}
。
要么:
模板<
布尔岛列表,类型名T,
typename容器=标准::条件\u t
>
自动创建容器()->Container
{
容器结果;
//我想,做两种容器都能用的东西
返回结果;
}
或:
模板
自动创建容器()
{
使用Container=std::conditional\u t;
容器结果;
//我想,做两种容器都能用的东西
返回结果;
}
我搬走了
#包括
#包括
为了简单起见,从我的示例中。正如MM所回答的,使用
std::conidtional
或专门化true
和false
模板函数或类型?
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