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

Templates instantiation from class members in C++

本文关键字:实例化 成员 C++      更新时间:2023-10-16

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

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的多个实例的可能性,以便使用这种类类型。如果我使j为静态,那么所有实例只有一个可能的值。有办法绕过这个吗?

实现这一点的唯一方法是使S中的j也依赖于模板参数。
template<int I>
class S {
public:
    static const int j = I;
...
}

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