Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I give template arguments to an object created inline with its class?

I know that in C++ we can do this:

class A {} a;

This makes an object of type A named a. It's equivalent to:

A a;

I was wondering how I would do this with templates. For example:

template <typename T> struct N {} <int> n;

This doesn't compile, but you get the idea. How would I specify the template arguments to an object created inline with its class definition? Is this even possible?

like image 238
template boy Avatar asked Dec 24 '12 16:12

template boy


People also ask

Are template specializations inline?

An explicit specialization of a function template is inline only if it is declared with the inline specifier (or defined as deleted), it doesn't matter if the primary template is inline.

How do you use template arguments in C++?

A template argument for a template template parameter is the name of a class template. When the compiler tries to find a template to match the template template argument, it only considers primary class templates. (A primary template is the template that is being specialized.)

What is template argument deduction in C++?

Class Template Argument Deduction (CTAD) is a C++17 Core Language feature that reduces code verbosity. C++17's Standard Library also supports CTAD, so after upgrading your toolset, you can take advantage of this new feature when using STL types like std::pair and std::vector.

What is the difference between Typename and class in template?

There is no difference between using <typename T> OR <class T> ; i.e. it is a convention used by C++ programmers.


2 Answers

The stuff after the closing } is called an init-declarator-list according to the standard.

14.3 explicitly forbids them to be used in template class declarations:

In a template-declaration, explicit specialization, or explicit instantiation the init-declarator-list in the dec- laration shall contain at most one declarator. When such a declaration is used to declare a class template, no declarator is permitted.

like image 172
Pubby Avatar answered Sep 21 '22 14:09

Pubby


I don't think you can do that. The form you mentioned, for structures and classes is kept, from my understanding, for backward compatibility with c - where you could do that for structs.
Nice idea, though :)

like image 31
Oren S Avatar answered Sep 19 '22 14:09

Oren S