开发者

Double template<> statements

开发者 https://www.devze.com 2023-04-13 08:15 出处:网络
There is such function definition: template<> template<> void object::test<1>() { } What does it mean that there are double template<>?

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<>开发者_JAVA技巧;
template<>
void object::test < 1 > () {
}

int main() {
    return 0;
} 

This code compiles under g++.

Source: TUT test framework


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
{ 
} 


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.


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>() 
{ 
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号