简体   繁体   中英

Pass templated class to templated function

I have a non-type templated class:

template<int N> class MyClass; // prototype

And a generic template function:

template<class T> Parameters validParams(); // prototype

What is the correct syntax to use a non-type templated class in a templated function? If I don't use a templated class, then the correct syntax is:

template<> Parameters validParams<MyClass>(); // prototype

I've looked around a bit to try to figure out what the syntax should be here, any help is appreciated! It would make the most sense to me if it were the following, but it's not...

template<> Parameters validParams<MyClass<int>>();

With this code I get the following error:

 expected a constant of size 'int', got 'int' 
 template<> Parameters validParams<MyClass<int>>(); 

Should be something like

template<> Parameters validParams<MyClass<42>>();
                                       // ^^

Take a look here.

MyClass<int> is not a type ( MyClass<42> , for example, is), while the function expects a name of a type (class) as a parameter. For it to be able to take a template as its template parameter , the syntax must be following:

template<template<typename> class T> Parameters validParams();

MyClass is a class templates whose template parameter is a value, not a type.

MyClass<0> is a valid instantiation of that template that results in a class.
MyClass<int> is not a valid instantiation of that template.

Hence, the line

template<> Parameters validParams<MyClass<int>>();

is not valid. A valid use will be:

template<> Parameters validParams<MyClass<0>>();

or

template<> Parameters validParams<MyClass<X>>();

as long as X is a compile time constant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM