7

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;
}
Sharkman
  • 117
  • 1
  • 2
  • 5
  • possible duplicate of [C++, template argument can not be deduced](http://stackoverflow.com/questions/6060824/c-template-argument-can-not-be-deduced) – Matthieu M. Mar 23 '12 at 20:03
  • (at least, a duplicate once solve the obvious `typename` issue, which VC++ would probably let slip as usual anyway) – Matthieu M. Mar 23 '12 at 20:04

2 Answers2

15

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*)'
josephthomas
  • 3,256
  • 15
  • 20
  • 2
    +1. Correct answer. The bigger problem is : `T` cannot be deduced, so it needs to be passed explicitly. – Nawaz Mar 23 '12 at 17:30
  • 2
    +1 I like newcomers giving "deep" answers! FYI the fact that `T` cannot be deduced here is known as **non-deducible context**. – Matthieu M. Mar 23 '12 at 20:03
3

It's a dependent name, you need to say:

template <typename T>
void func(typename Foo<T>::Bar* bar) // Tell the compiler explicitly it's a type
Community
  • 1
  • 1
Flexo
  • 87,323
  • 22
  • 191
  • 272
  • -1. This answer is incomplete, and doesn't solve the bigger problem in the question. What you said is true, but how would `func(&foo.bar_)` work? It still would not. – Nawaz Mar 23 '12 at 17:28