假设我有两个类(class)。第一个是简单的模板类 Point<N, T>
另一个是Function<Point<N, T>>
.是否可以在类 Function 中访问以键入 T
和 int N
.
这是我的 Point
我觉得还可以
template<int N, class T>
class Point {
public:
Point() {
std::fill(std::begin(data), std::end(data), T(0));
}
Point(const std::initializer_list<T> &init) {
std::copy(init.begin(), init.end(), std::begin(data));
}
public: // just for easier testing, otherwise protected/private
T data[N];
};
现在 Function
我认为有一些问题的实现
template<template<int, typename> class P, int N, typename T>
class Function {
public:
T operator()(const P<N, T> &pt) {
for (int i = 0; i < N; i++) {
// do something and expect loop unrolling
}
return T(0); // for example's sake
}
T operator()(const P<N, T> &pt1, const P<N, T> &pt2) {
// force pt1 and pt2 to have the same `N` and `T`
return T(0); // for example's sake
}
};
这就是我想象的如何使用我的类(class)。也许我想太多了 java-like :)
typedef Point<3, float> Point3f;
typedef Point<4, float> Point4f;
Point3f pt3f({ 1.0, 2.0, 3.0 }); // Point<3, float>
Point4f pt4f({ 1.0, 2.0, 3.0, 4.0 }); // Point<4, float>
Function<Point3f> f3; // Function<Point<3, float>> f3;
float val = f3(pt3f); // no error
float val = f3(pt3f, pt3f); // no error
float val = f3(pt4f); // compile error
float val = f3(pt4f, pt3f); // compile error
我怎样才能实现这样的行为?我不断收到类似 "Point<3, float>" is not a class template
的错误或 too few arguments for class template "Function"
最佳答案
template<class Point>
class Function;
template<template<int, typename> class P, int N, typename T>
class Function<P<N,T>>
替换:
template<template<int, typename> class P, int N, typename T>
class Function
解决了你的语法问题。
关于c++ - 模板模板参数访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34801769/