Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there ever a reason to use "::template"?

You can use the template keyword when getting a template name from a global namespace:

template <class T> void function_template();

template <class T>
void h()
{
    ::template function_template<T>();
}

int main() { h<int>(); }

But this code can compile without it. What are the situations in which one might want to do this?

like image 526
template boy Avatar asked Jan 18 '15 04:01

template boy


1 Answers

I can think of one place, but I hardly think it would be common:

#include <iostream>

// simpile function template
template<class T>
void function_template(T)
{
    std::cout << __PRETTY_FUNCTION__ << '\n';
}

// overload (NOT specialized)
void function_template(int value)
{
    std::cout << __PRETTY_FUNCTION__ << '\n';
}

int main()
{
    function_template(0);               // calls overload
    ::function_template(0);             // calls overload
    ::template function_template(0);    // calls template, deduces T
}

Output

void function_template(int)
void function_template(int)
void function_template(T) [T = int]

I was going to stuff some of this in an anonymous namespace to actually bring non-trivial meaning to :: but this seems to be sufficient so I left it out.

like image 150
WhozCraig Avatar answered Oct 09 '22 23:10

WhozCraig