passing parameter to a template

How can I pass a parameter (a phrase) to a template class?

I want my class to behave differently if I specify MyObject<runPartA> obj and MyObject<runPartB> obj.
1
2
3
4
5
6
7
8
9
template<char * phrase>
class SomeClass
{
public:
    SomeClass()
    {
        if (!strcmp(phrase, "This is it!")).....
    }
};
That seems awfully hokey. What are you trying to accomplish?
template<const char * phrase>

*cough*cough*

Also, +1 jsmith
Last edited on
Soooorry Disch! hehe. I've never done this stuff so I missed the delicate details here and there. Just like jsmith, I too find this hokey (after looking up the Sunday word in the dictionary, that is :D ).
is there any advantage to using a const char* over a const string&? I've always stayed away from char*s.
About 50% of that class is going to be repeated for runPartA and runPartB. So I am trying to reuse the code.
webJose idea works but it would be nice to write SomeClass<ThisIsIt> instead of SomeClass<"This is it!">. It looks much better. How can I do that?
Last edited on
Make empty structs as tags.

1
2
3
4
5
6
7
8
struct RunPartA {};
struct RunPartB {};

template< typename T >
class SomeClass
{
   // ...
}


Though I'd consider moving as much of the functionality from SomeClass's constructor into functions within RunPartA and RunPartB as I could without duplicating code. It is probably OK even to tightly couple RunPartA, etc to SomeClass at that point because users probably won't instantiate RunPartA etc directly.

Or so I'm conjecturing based on the limited info available.

Just a thought.

To quirkyusername: yes, there is, if it is to be a template parameter, since template parameters must be constants. The std::string approach won't compile with it as a template parameter.

EDIT: on second thought, I still don't like the idea. It basically means checking typeof(T) for each possible value of T in the constructor. This smacks of either runtime polymorphism (derivation) or of template class specialization, however in the specialization case, you'll end up with a lot of code duplication if the class is big, unless you can factor most of it into say, a base class, or some other class.

Last edited on
Enumerations would be simpler (I think?) than empty structs. Still, I don't like this either. I see no gains whatsoever. The idea of a template is to allow the programmer to delegate the actual writing of code that is the same for different data types or values. I don't see how the OP's issue fits the bill here because I sense that the template will use a switch() or an if () to route code one way or another. So where is the gain??
Yes, now I see that this wasn't such a good idea. Adding two separate methods solved the problem.
Last edited on
Topic archived. No new replies allowed.