c++ - 模板模板参数访问

标签 c++ oop templates c++11 generics

假设我有两个类(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/

相关文章:

c++ - 重复的 C++ 模板实例化

c++ - 模板类派生自非模板基类 : No access to base class variables?

c++ - 了解构造函数的一些具体情况

c++ - 如何检查输入是否为整数/字符串?

c++通过一个函数修改多个数组

java - LibGDX无法访问内部图像资源

c# - 类型约束

c++ - 如何在 FreeLibrary 调用后强制 Visual Studio 2015 解锁 .PDB 文件?

java - 子类在抽象父类(super class)中使用不同的构造函数实现公共(public)方法

ruby - 模板方法模式,在哪里定义常用函数