在编译时选择一个变量
Select a variable at compile-time
我希望能够通过布尔来指定我需要在编译时间使用的两个变量中的两个变量,所有这些都不直接sfinae 。只有一个功能,类似于std::conditional
,但不返回类型。
所以例如在test
中,我想拥有
class test
{
template <class T, bool first, MAGIC_HAPPENS var>
void apply_it(T &t)
{
for (auto &p : var) p.apply(t);
}
std::vector<myfunction> var1;
std::vector<myfunction> var2;
}
使用很简单:如果我指定first == true
,则应使用var == var1
应用循环,否则var == var2
。
可能吗?
只是为了娱乐(*), minimal c 17(**)对当前代码段的修改可能是
class test
{
std::vector<myfunction> var1;
std::vector<myfunction> var2;
template <class T, bool first, std::vector<myfunction> test::*var = first ? &test::var1 : &test::var2 >
void apply_it(T &t)
{
for (auto &p : this->*var) p.apply(t);
}
};
(*)我没有看到这样的事情比其他建议的解决方案更可取的情况...
(**)据我所知,由于模板的连锁要求非类型指针参数...
for C 17及以上:
class test
{
template <class T, bool first>
void apply_it(T &t)
{
if constexpr (first)
{
for (auto &p : var1) p.apply(t);
}
else
{
for (auto &p : var2) p.apply(t);
}
}
std::vector<myfunction> var1;
std::vector<myfunction> var2;
}
if constexpr
如果条件为constexpr,则在编译时间进行评估,模板参数就是这种情况。
您可以在C 11中使用指向数据成员的指针:
class test
{
template <class T, bool first>
void apply_it(T &t)
{
constexpr auto var = first ? &test::var1 : &test::var2;
for (auto &p : this->*var) p.apply(t);
}
std::vector<myfunction> var1;
std::vector<myfunction> var2;
}
template<std::size_t I, class...Args>
decltype(auto) pick( Args&&... args ) {
return std::get<I>( std::forward_as_tuple( std::forward<Args>(args)... ) );
}
pick
在列表中选择某些内容。
class test
{
template <bool first, class T>
void apply_it(T&& t)
{
auto&& var = pick<first?0:1>(var1, var2);
for (auto&& p : var)
p.apply(t);
}
std::vector<myfunction> var1;
std::vector<myfunction> var2;
};
我在复制粘贴时也做出了一些小改进。
相关文章:
- 用C++中的一个变量定义一个常量
- 一个变量的输入值也会保存到另一个变量中
- 将双精度变量设置为另一个变量的值
- 对具有相同方法的不同类使用一个变量
- 为什么一个变量获得与另一个值相同的值
- 尝试在 C++ 中为 ifstream 提供一个变量
- 类中的一个变量显示,但另一个不显示
- 声明一个变量,该变量在 c++ 或 c 中具有值,当程序终止时不会被销毁
- c++问题:给一个变量赋值后,另一个变量发生了变化
- 如何将一个变量用于父类和派生类
- 如何在循环中使用scanf,将值存储到一个变量中,然后打印出来?
- 我如何将一个变量与另一个变量进行比较,例如我想如果(var1 > var2 x 1),然后执行此 c++
- 如何在一个函数中定义一个变量,并在另一个函数中访问和更改它?(C++)
- 如果一个变量在它之前释放了另一个(相同的数据类型)变量,如何将其分配给内存?
- 迭代器或反向器的一个变量
- fstream库,试图创建一个变量名为(c++)的文件
- 如何在 c++ 中将两个不同类型的变量分配给一个变量
- 如何将一些变量放在一个变量中?
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 如何用索引命名一个变量来存储输入 mxArray?