C++ 中 class 成员的模板实例化

Templates instantiation from class members in C++

我正在尝试创建一个数据对象(class 或结构),其中包含用于实例化模板 classes 的编译时已知值。也许这在以下示例中变得更加清楚:

class S
{
public:
    const int j;
    ... constructor
    // Must contain member to later instantiate templates.
    // Defining these members must be forced
    // Defined at compile time
}

template<int I>
class C {...}

int main(){
    S s(10);
    S s2(20);
    // now create some class from the field in s
    C<s.j>  c(...)
    C<s2.j> c2(...)
}

这只有在成员 j 是静态的情况下才有效,对吧?但是,我想创建定义 S 的多个实例的可能性,以使用此 class 类型。如果我将 j 设为静态,则所有实例都只有一个可能的值。有办法解决这个问题吗?

做到这一点的唯一方法是使 S 中的 j 也依赖于模板参数。

template<int I>
class S {
public:
    static const int j = I;

...
}

您不能将运行时值(class 成员)作为模板参数传递。