-2

I know this question has been asked numerous times, but referring to the answer to this question: How can I specialize a template member function for std::vector<T>

if I try a simple example of this using GCC9 it simply does not work, and I cant understand why not. Am I missing something here?

#include <vector>
#include <stdio.h>

template<typename T>
std::vector<T> foo( const std::vector<T> & )
{
    printf( "vector!\n" );
    return std::vector<T>();
}

template<typename T>
T foo( const T & )
{
    printf( "non vector!\n" );
    return T();
}

int main()
{
    foo<int>( *( int * ) nullptr);
    foo<std::vector<int>>( *( std::vector<int> * ) nullptr);
}

Outputs:

non vector!
non vector!
ByteMe95
  • 836
  • 1
  • 6
  • 18
  • 3
    Your template parameter `T` is the type of the vector's elements, and you're not passing a `std::vector>`. (Explicit instantiations can be surprising.) – molbdnilo Nov 09 '20 at 15:14

1 Answers1

2

Try changing:

foo<std::vector<int>>( *( std::vector<int> * ) nullptr);

to

foo<int>( *( std::vector<int> * ) nullptr);

Your top template expects a typename T and the method takes a vector of T.

Joseph Larson
  • 8,530
  • 1
  • 19
  • 36
  • 1
    Even better, let template parameters be deduced. – Guillaume Racicot Nov 09 '20 at 15:26
  • @GuillaumeRacicot I'd love to see an example, as I'm not sure what you're suggesting. – Joseph Larson Nov 09 '20 at 15:27
  • 3
    Something like `std::vector someVector; foo(someVector);` without explicitly specifying the template parameter at all. But that does require you to know a lot about how overload resolution interacts with templated functions to be confident that `foo(someVector)` will call the first function with `T = int` and not the second function with `T = std::vector`. – Nathan Pierson Nov 09 '20 at 15:34
  • Thanks! I totally missed this since i was originally calling with <> ( without the T* argument ) and then neglected to consider the call site when I changed this – ByteMe95 Nov 09 '20 at 16:44