Lucretiel
Lucretiel

Reputation: 3324

Access class template variable outside of class

I have a class like this:

template<char _character>
class Foo
{
    ...
public:
    static const char character = _character;
};

Is there a way I can access the _character parameter outside the class, without the static to forward it? Something like Foo::_character.

Upvotes: 1

Views: 314

Answers (2)

Steve Lorimer
Steve Lorimer

Reputation: 28659

Short answer is no, you can't.

_character is the template parameter, and is unknown until you instantiate the template.

After instantiation _character is no longer a member of your concrete instantiation, but rather the char you passed in is.

By creating static const char character = _character; you are creating a char data member which is dependent on the template parameter used to instantiate your class template.

You can now access said data member from an instantiated class template:

typedef Foo<'c'> CFoo;
std::cout << CFoo::character << std::endl;

Once you instantiate the class template, Foo<'c'>::_character doesn't exist.

Upvotes: 2

Pubby
Pubby

Reputation: 53027

You can use pattern matching:

template<typename T>
struct get_character;
template<char _character>
struct get_character<Foo<_character> > {
    static const char character = _character;
};

To use:

get_character< Foo<'a'> >::character

Upvotes: 1

Related Questions