Experiment with unnamed namespace and template

  • Thread starter Johannes Schaub (litb)
  • Start date
J

Johannes Schaub (litb)

I have this code:

namespace {
template <class T>
struct Template { /* ... */ };
}

typedef Template<int> Template;


Can we put code after it to create an object of type `Template<float>`?
Reopening the unnamed namespace is not allowed. All code should be
afterwards!

I think there are a couple of solutions. What are the most crazy ones?
 
V

Victor Bazarov

I have this code:

namespace {
template<class T>
struct Template { /* ... */ };
}

typedef Template<int> Template;

So, the name ::Template refers to the typedef, then.
Can we put code after it to create an object of type `Template<float>`?
Reopening the unnamed namespace is not allowed.

What do you mean by "not allowed"?
> All code should be
afterwards!

I think there are a couple of solutions. What are the most crazy ones?

namespace {
template <class T>
struct Template { /* ... */ };
}

typedef Template<int> Template;

// reopening - miracle!
namespace {
typedef Template<float> fTemplate;
}

int main()
{
::Template a; // creates an object of type Template<int>
fTemplate f; // here is your Template<float>
}


V
 
L

Luc Danton

I have this code:

namespace {
template<class T>
struct Template { /* ... */ };
}

typedef Template<int> Template;


Can we put code after it to create an object of type `Template<float>`?
Reopening the unnamed namespace is not allowed. All code should be
afterwards!

I think there are a couple of solutions. What are the most crazy ones?

I did:

namespace {

template<class T>
class Template {};

} // namespace

typedef Template<int> Template;

template<typename Target, typename Source, typename T>
struct retarget;

template<
typename Target,
typename Source,
template said:
struct retarget<Target, Source, T<Source> > {
typedef T<Target> type;
}

int
main()
{
retarget<float, int, ::Template>::type();
}

It compiled fine in C++03 conformant mode. (Note that as I tested the
code on another machine so it is not copied verbatim, there might be
errors in the above.) I then added an explicit specialisation
Template<float> with a static_assert inside to check the right type was
being instanciated and it was triggered. (In C++0x mode this time for
static_assert.)

Doesn't seem that crazy to me though.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,222
Members
46,810
Latest member
Kassie0918

Latest Threads

Top