Thread: Template class with variable parameters.

  1. #1
    Registered User
    Join Date
    Jun 2007

    Template class with variable parameters.

    Suppose I have a template class:
    template<class A, int B>
    class foo
    is it possible to instantiate the template class with a variable in the second paramter?
    int variable=99;
    foo<apples, variable> foo1=new foo();
    , where apples is a class.

    My compiler doesn't let me do it as above; it requires the second parameter to be a constant.

    Last edited by cybernike; 06-29-2007 at 10:41 PM.

  2. #2
    Registered User
    Join Date
    Jan 2005
    It must be a compile-time constant. Templates are resolved at compile time. A different class foo is created for each different set of parameters you give it, so the compiler must know the parameter values when it is compiling.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    I do not think so, since the template must be instantiated at compile type, and a variable's value may be determined at runtime.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Access protected base class template variable
    By pjotr in forum C++ Programming
    Replies: 4
    Last Post: 11-06-2007, 05:34 AM
  2. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  3. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  4. using class as template variable
    By hiya in forum C++ Programming
    Replies: 17
    Last Post: 04-19-2005, 04:17 AM
  5. Variable Allocation in a simple operating system
    By awkeller in forum C Programming
    Replies: 1
    Last Post: 12-08-2001, 02:26 PM