Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax for specializing function templates

Is there a difference between the following approaches?

// approach 1
namespace std
{
    template<>
    void swap<Foo>(Foo& x, Foo& y)   // note the <Foo>
    {
        x.swap(y);
    }
}

// approach 2
namespace std
{
    template<>
    void swap(Foo& x, Foo& y)
    {
        x.swap(y);
    }
}

I stumpled upon this when I tried to specialize swap for my own string type and noticed that swap<::string> doesn't work, but for a completely different reason :)

like image 798
fredoverflow Avatar asked Apr 30 '10 20:04

fredoverflow


People also ask

What is the syntax of function template?

A function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.

How do you define a template specialization in C++?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.

How do I create a function template?

To instantiate a template function explicitly, follow the template keyword by a declaration (not definition) for the function, with the function identifier followed by the template arguments. template float twice<float>( float original ); Template arguments may be omitted when the compiler can infer them.

What is function template explain its syntax and semantics?

- We can define a template for a function that can help us create multiple versions for different data types. - A function template is similar to a class template and it syntax is as follows : template <class T> Return-type functionName (arguments of type T)


1 Answers

Yes, there is. But not in that particular example. If the parameter is not deduced, it can make a difference

template<typename T> void f(typename T::type t);

You cannot specialize that without <type> because it cannot deduce what T is from the parameter list.

struct MyType { typedef int type; };

// needs <MyType>
template<> void f<MyType>(int t) { }

Of course in your case, it's the digraph <: that's meaning the same as [ causing your problem. Put a space like < ::string> to avoid the problem.

like image 102
Johannes Schaub - litb Avatar answered Sep 28 '22 08:09

Johannes Schaub - litb