Click here to Skip to main content
15,881,687 members
Articles / Programming Languages / C++
Alternative
Tip/Trick

Passing a const character * as a template argument

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
4 Jul 2011CPOL 6.3K  
Provided that the intent is to associate a string (const char *) with a particular dialog type, an implementation like this one could be used.templatestruct CVHDialogTmpl{ CVHDialogTmpl() { } INT_PTR DoModal() { return t.DoModal(ptr); } ...
Provided that the intent is to associate a string (const char *) with a particular dialog type, an implementation like this one could be used.

C++
template<class Ty>
struct CVHDialogTmpl
{
    CVHDialogTmpl()
    {
    }
    INT_PTR DoModal()
    {
        return t.DoModal(ptr);
    }
    Ty t;
    static const char * const ptr;
};

template <class Ty>
const char * const CVHDialogTmpl<Ty>::ptr = "Generic text";

struct A { /* */ };
struct B { /* */ };
struct C { /* */ };

const char * const CVHDialogTmpl<A>::ptr = "Text for A";
const char * const CVHDialogTmpl<B>::ptr = "Text for B";


A possible variation to allow custom text to be used would be to make the following changes:
C++
template<class Ty>
struct CVHDialogTmpl
{
    CVHDialogTmpl() : actualText(ptr)
    {
    }
    CVHDialogTmpl(const char *customText) : actualText(customText)
    {
    }
    INT_PTR DoModal()
    {
        return t.DoModal(actualText);
    }
    Ty t;
    const char *actualText;
    static const char * const ptr;
};


In practice, that final solution is far better if there might be a situation where the text might sometimes differ. Assuming that the text is a filename for the dialog template, then most of the time the template associated to that type would be used but if in some situation a different template should be used then the constructor with one argument could be used.

By using a function and typeid/typeinfo, this solution could easily be extended to provide a text that depends on the type, thus if some convention are followed like the filename should be the struct/class name without the leading capital letter if it is C and followed by another capital letter, it would be possible to not specify it explicitly for that type. This would be compiler specific as the returned name might vary... In that case, the actual text to use might be stored in a std::string.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Canada Canada
Programmer at Maid LABS from 2003 (www.maidlabs.com)

Programmer-Analyst at Viasat Geo Technoligies from 1995 to 2002 (www.viasat-geo.com).

I have studied at École Polytechnique de Montréal in computer engineering.

Comments and Discussions

 
-- There are no messages in this forum --