Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local type as template arguments in C++ [duplicate]

Tags:

c++

templates

This is my code

#include <vector> template <typename T, template<typename> class C = std::vector > struct FooBar {    /*codez*/ }; template<typename T> struct Global{};  int main() {    struct Local{};      FooBar<Local,Global> k; } 

This is the error that I get

template argument for ‘template<class T, template<class> class C> struct FooBar’ uses local type ‘main()::Local’

Which part of the standard says that this is wrong? I am using gcc 4.5.1. How can make this code work?

like image 609
Ron Kanga Avatar asked Apr 22 '11 03:04

Ron Kanga


People also ask

Can we pass Nontype parameters to templates?

Template non-type arguments in C++It is also possible to use non-type arguments (basic/derived data types) i.e., in addition to the type argument T, it can also use other arguments such as strings, function names, constant expressions, and built-in data types.

CAN default arguments be used with the template?

You cannot give default arguments to the same template parameters in different declarations in the same scope. The compiler will not allow the following example: template<class T = char> class X; template<class T = char> class X { };

Can template parameters have default values?

Just like in case of the function arguments, template parameters can have their default values. All template parameters with a default value have to be declared at the end of the template parameter list.

What is the difference between template class and template Typename?

2: There is no semantic difference between class and typename in a template-parameter. typename however is possible in another context when using templates - to hint at the compiler that you are referring to a dependent type.


1 Answers

Which part of the standard says that this is wrong?

That would be §14.3.1/2 from the 2003 C++ Standard:

A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.


How can make this code work?

Don't use a local type as a template argument.

Note that this restriction has been lifted in C++11, so using that language standard you are able to use a local type as a template argument.

like image 122
James McNellis Avatar answered Sep 28 '22 10:09

James McNellis