Home Passing an instance of a user defined template class to a non templated function
Reply: 2

Passing an instance of a user defined template class to a non templated function

Chani
1#
Chani Published in 2018-01-10 00:41:04Z

I have following implementation:

#include <cstddef>

template<typename Data, size_t Size> 
class Demo
{  
public:
    Demo();

private:
    Data data[Size];
};

void f(Demo<int, size_t>& demoObj)
{

}


int main()
{
    Demo<int, 100> demoObj;

}

I get the following error when I compile:

g++ -std=c++11 temp.cpp
temp.cpp:13:24: error: type/value mismatch at argument 2 in template parameter list for ‘template<class Data, long unsigned int Size> class Demo’
 void f(Demo<int, size_t>& demoObj)
                        ^
temp.cpp:13:24: note:   expected a constant of type ‘long unsigned int’, got ‘size_t {aka long unsigned int}’

The error is not making sense to me. Please help me understand it. Also, how do I pass demoObj to function f? I mean how o write the definition of f.

Kerrek SB
2#
Kerrek SB Reply to 2018-01-10 00:57:45Z

Size is a non-type parameter, so it requires a non-type argument:

void f(Demo<int, 100>& demoObj);
//               ^^^
super
3#
super Reply to 2018-01-10 01:13:27Z

If you want to be able to pass in any kind of Demo you can define f as a template function.

template<typename Data, size_t Size>
void f(Demo<Data, Size>& demoObj)
{
    // ...
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.504092 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO