Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As mfontanini explains (and your compiler complains), non-type template parameters have to be compile-time constants. And your attempt to fool it by "const int p = i;" doesn't help; p may be constant variable, but it's not a compile-time constant. A C++11 compiler can do a better job telling you what's wrong here, but it can't help you get around the problem. In fact, there is no direct way around the problem.</p> <p>The simplest solution is an explicit switch, as user315052 suggests. And, if you're only doing this once, and just switching on 1 vs. 2, it's not worth putting in more effort than that.</p> <p>If you're doing the switch lots of times, of course, it's trivial to wrap it in a function:</p> <pre><code>void bar(int i) { switch(i) { case 1: foo(userInput&lt;1&gt;::typeName()); return; case 2: foo(userInput&lt;2&gt;::typeName()); return; default: throw someException; } </code></pre> <p>But if you have a lot more than 2 cases, or the set of values is in constant flux, you'll definitely want to use Boost.Preprocessor to automate the cruft, which would look something like this:</p> <pre><code>#define FOO_CASES_ 50 #define FOO_PASTE_(rep, i, _) case i: foo(userInput&lt; i &gt;::typeName()); return; void bar(int i) { switch (i) { BOOST_PP_REPEAT(FOO_CASES_, FOO_PASTE_, _) default: throw someException; } } #undef FOO_CASES_ #undef FOO_PASTE_ </code></pre> <p>Or, alternatively, write a code generator that creates a .cpp file for you to compile:</p> <pre><code>#!/usr/bin/env python with file('bar.cpp', 'w') as f: f.write('void bar(int i) {\n') f.write(' switch(i) {\n') for i in range(50): f.write(' case %d: foo(userInput&lt;%d&gt;::typeName()); return;\n' % (i, i)) f.write(' default: throw someException;\n') f.write(' }\n') f.write('}\n') </code></pre> <p>Yet another alternative is to create a lookup array (or vector) that's initialized with the appropriate objects/functions/whatever, so you can use *userInputLookup[i] in place of userInput. But without knowing the exact use case, and whether you're using C++11, it's hard to give details.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload