By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,190 Members | 944 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,190 IT Pros & Developers. It's quick & easy.

template instantiation with local type

P: n/a
Hello all,

Is there a way to pass an object of local type to a template?

template <class T> int fun(const T& x) { return 1; }

int bar()
{
enum Color { Red, Green, Blue};
Color c;
fun(c); // Error, Color is local to bar()
}

Dec 9 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
Neelesh Bodas wrote:
Hello all,

Is there a way to pass an object of local type to a template?


No. If you want to use a type as template argument, that type must have
external linkage, and local types don't have any linkage.

Dec 9 '05 #2

P: n/a

Rolf Magnus wrote:
No. If you want to use a type as template argument, that type must have
external linkage, and local types don't have any linkage.


Great. Thanks.

Dec 9 '05 #3

P: n/a

Neelesh Bodas wrote:
Hello all,

Is there a way to pass an object of local type to a template?

template <class T> int fun(const T& x) { return 1; }

int bar()
{
enum Color { Red, Green, Blue};
Color c;
fun(c); // Error, Color is local to bar()
}


No. The usual workaround is to place the declarations in an anonymous
namepspace:

template <class T>
struct TemplateClass
{
};

namespace
{
enum Color { Red, Green, Blue};
Color c;

}

int main()
{
TemplateClass<file_scope_type> a;

//...
}

An anonymous namespace essentially allows local types at the file level
to be used as template type parameters.

Greg

Dec 10 '05 #4

P: n/a
Neelesh Bodas wrote:
Hello all,

Is there a way to pass an object of local type to a template?

template <class T> int fun(const T& x) { return 1; }

int bar()
{
enum Color { Red, Green, Blue};
Color c;
fun(c); // Error, Color is local to bar()
}


No. The usual suggestion is to place the declarations in an anonymous
namespace:

template <class T> int fun(const T& x) { return 1; }

namespace {
enum Color { Red, Green, Blue};
}

int main()
{
Color c;

fun(c); // OK, Color is unique to local file
}

An anonymous namespace essentially allows local types at the file level
to be used as template type parameters.

Greg

Dec 10 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.