template instantiation with local type

N

Neelesh Bodas

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()
}
 
N

Neelesh Bodas

Rolf said:
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.
 
R

Rolf Magnus

Neelesh said:
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.
 
G

Greg

Neelesh said:
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
 
G

Greg

Neelesh said:
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
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top