Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a typename nested in a template parameter

This is a mouthful, so here's a piece of code as an example:

template<typename T>
void foo(const T& a, typename T::value_type::value_type b) { }

std::vector<std::vector<int>> vec;
foo(vec, 4); // Error, can't specialize function template

This compiles and runs correctly using gcc. It doesn't compile using Visual Studio 2010, for the reason commented above. However, if the final value_type is prefixed with the template keyword, it will compile and run correctly. I have a few guesses as to why, but can't find the relevant section of the standard.

template<typename T>
void foo(const T& a, typename T::value_type::template value_type b) { }

std::vector<std::vector<int>> vec;
foo(vec, 4); // Compiles and runs correctly with Visual Studio 2010

I'm aware that the above usage of template is a Visual Studio extension, but what does the standard say about using types like this? Is gcc's acceptance of the code also an extension, or is this a deficiency on Visual Studio's part?

like image 672
Collin Dauphinee Avatar asked Oct 11 '22 06:10

Collin Dauphinee


1 Answers

This is absolutely a deficiency on VC++ 2010's part – std::vector<int>::value_type is a type, not a template, and should not be decorated as such. In fact, use of that syntax in this context should cause a compiler error.

Supporting evidence is that the following does compile (as it should):

#include <vector>

template<typename T>
void foo(T const& a)
{
    typename T::value_type::value_type bar = a.at(0).at(0);
}

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

and the following doesn't (as it shouldn't):

template<typename T>
void foo(T const& a)
{
    typename T::value_type::template value_type bar = a.at(0).at(0);
}

The resulting error being

error C2903: 'value_type' : symbol is neither a class template nor a function template

I recommend opening a bug report on MS Connect and posting the link back here so we can vote it up.

like image 65
ildjarn Avatar answered Oct 14 '22 03:10

ildjarn