Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template function taking template class as parameter

I'm struggling with the following code. Basically, I have a class Foo and nested class Bar, and now I want to pass a pointer of class Bar object to a function, but it doesn't compile. Could anyone help me with this? Thank you.

template <typename T>
struct Foo
{
    struct Bar
    {
        T data_;
    };
    Bar bar_;
};

template <typename T>
void func(Foo<T>::Bar* bar) // Why is this line wrong???
{
}

int main()
{
    Foo<int> foo;
    foo.bar_.data_ = 17;
    func(&foo.bar_);
    return 0;
}
like image 948
Sharkman Avatar asked Mar 23 '12 17:03

Sharkman


People also ask

Can a template be a template parameter?

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.)

Can a template parameter be a function?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

Why do we use :: template template parameter?

8. Why we use :: template-template parameter? Explanation: It is used to adapt a policy into binary ones.

How do you call a function template?

Defining a Function TemplateA function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.


1 Answers

You need to have the following signature

template <typename T>
void func(typename Foo<T>::Bar* bar) // Why is this line wrong???

However, that is not the only problem

func(&foo.bar_);

also needs to be

func<int>(&foo.bar_);

This is because you are calling the templated function "func" but its type can not be deduced. Without its type, it will give an error such as

no matching function for call to 'func(Foo<int>::Bar*)'
like image 94
josephthomas Avatar answered Nov 29 '22 21:11

josephthomas