Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double template<> statements

Tags:

c++

There is such function definition:

template<>
template<>
void object::test<1>()
{
}

What does it mean that there are double template<>?

EDIT:

I extracted code which is valid for this example:

#include <iostream>

template <class U>
class A {

    template <int n>
    void test() {

    }
};

template <class T>
class B {
public:
    typedef A<T> object;
};

typedef B<int>::object object;

template<>
template<>
void object::test < 1 > () {
}

int main() {
    return 0;
} 

This code compiles under g++.

Source: TUT test framework

like image 762
scdmb Avatar asked Oct 17 '11 13:10

scdmb


3 Answers

For example,

template<class T = int> // Default T is int
class object<T> {
   template<int R> void test ();
};

Your code:

template<> // T is fixed
template<> // R is fixed
void object<>::test<1>() // T is default int, R is 1
{
}

is equivalent to:

template<> // T is fixed
template<> // R is fixed
void object<int>::test<1>() // T is int, R is 1
{ 
} 
like image 171
Alexey Malistov Avatar answered Oct 20 '22 15:10

Alexey Malistov


This is the template specialization of a class template member function template (did I get that right?), with a default parameter for the template. Look at this:

template<typename T = int>
struct X {
  template<typename U>
  void foo(U u);
};

template<>
template<>
void X::foo(float f) { }

This introduces a specialization for the case where the template parameter of X is int and the argument to X<int>::foo is float. This case is slightly different from yours, we don't have to provide the template argument explicitly after the name of the member function as it can be deduced. Your function has a non-type template argument which cannot be deduced and as such must be provided.

What confused me the most is the default template argument and I'm unsure if it is good practice to use skip it. I'd provide it for every specialization to avoid confusion.

like image 34
pmr Avatar answered Oct 20 '22 14:10

pmr


That looks to me like a specialization of a function template within a class template. For example, consider the following class template definition:

template <int m=1>
class object
{
public:
  template <int n>
  void test();
};

// This differs from your example, by the addition of `<>` after `object`, but it's as
// close as I can come to valid code true to your example
template<> 
template<> 
void object<>::test<1>() 
{ 
} 
like image 23
Michael Goldshteyn Avatar answered Oct 20 '22 13:10

Michael Goldshteyn