模板参数简化
Template parameters simplification
本文关键字:参数 更新时间:2023-10-16
我对c++相当陌生(使用c++ 2011),我想为以下问题找到解决方案。我有一个表示函数的类:
class Curve {
private:
...
public:
std::array<double, 3> value(double s);
}
我使用该对象将这个函数传递给一个算法,该算法由一个类表示:
template <int n, typename Functor>
class Algorithm {
private:
Functor f;
std::array<double, n> a;
public:
...
}
然后创建对象
Algorithm<3, Curve> solver;
但是3显然是来自于任何Curve类型对象的方法值所返回的数组的大小。我想简化这段代码,以便我可以使用:
Algorithm<Curve> solver;
但是我不知道该怎么做。你介意给我个提示吗?
最诚挚的问候,弗朗索瓦
添加成员array_length
或类似Curve
的类:
class Curve
{
public:
static constexpr const std::size_t length = 3;
private:
std::array<double,length> a;
};
template<typename ALGORITHM , std::size_t n = ALGORITHM::length>
class Algorithm
{
...
};
如果你需要允许经典函数实体作为算法,这种方法不起作用,因为没有length
成员。另一种方法是创建一个元函数data_length
给定一个算法函数F
,返回数据的长度:
template<typename F>
struct length;
//Specialization for Curve class:
template<>
struct length<Curve> : public std::integral_constant<std::size_t,3>
{};
然后:
template<typename F , std::size_t n = length<F>::value>
struct Algorithm
{
...
};
EDIT:与其他模板一样,要实现该方法,请指定其模板参数:
template<typename F , std::size_t N>
void Algorithm<F,N>::execute()
{
_f();
}
使用decltype
来获取value
的返回类型,使用std::tuple_size
来查看它的大小(Live at Coliru):
template <typename Functor>
class Algorithm {
private:
Functor f;
static const std::size_t n =
std::tuple_size<decltype(f.value(0.))>::value;
std::array<double, n> a;
public:
// ...
};
或者如果您只是希望a
具有与value
返回的相同类型:
template <typename Functor>
class Algorithm {
private:
Functor f;
decltype(f.value(0.)) a;
public:
// ...
};
或者如果有一天你想使用不同类型的函数——比如int
或long long
或其他类型的函数——你可以在调用f.value
时使用默认构造值(无论它的参数类型是什么)来请求返回类型:
template <typename Functor>
class Algorithm {
private:
Functor f;
decltype(f.value({})) a;
public:
// ...
};
你可以像这样在枚举成员中"传递" 3:
class Curve {
public:
enum { arity = 3 };
std::array<double, arity> value(double s);
};
template <typename Functor>
class Algorithm {
private:
std::array<double, Functor::arity> a;
};
Curve curve;
Algorithm<Curve> solver;
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- 使用指向成员的指针将成员函数作为参数传递
- 没有名称的C++模板参数
- 如何将enable-if与模板参数和参数包一起使用