简体   繁体   中英

Templates instantiation from class members in C++

I am trying to create a data object (class or struct) which contains compile time known values to instantiate template classes with. Maybe this becomes more clear in the following example:

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(...)
}

This will only work if the member j is static, right? However, I want to create the possibility of defining multiple instances of S, to work with this class type. If I make j static, there is only one possible value for all instances. Is there a way to get around this?

the only way to do this, is to make j in S dependant from a template argument, too.

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

...
}

you can not pass runtime values (class members) as template arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM