weggo
weggo

Reputation: 134

Typedef with template functions

Say I have a template function in namespace A. I also have another namespace B. There is a template function declared in namespace A, which is defined as

template<typename T, typename U>
void f(T a, U b);

Now in namespace B, I would want to declare a specialized type of the template function. I was thinking if I could typedef the template function so it is declared in namespace B as

void f(int a, double b);

without actually implementing the function calling the template function. As there is a way to declare new typenames with specific template parameters, shouldn't there be a way to do that with functions aswell? I tried different methods to achieve it, but it didn't quite work out.

So is there already a way in C++ to redeclare the function with given template parameters without actually implementing a new function? If not, is it somehow achievable in C++11?

It would be a neat feature to have since it would make the purpose of the function more clear and would be syntactically better :)

Edit: So one could write:

using A::f<int, double>;

in B namespace and the function would show up with those template parameters

Upvotes: 3

Views: 5322

Answers (2)

Andrew Tomazos
Andrew Tomazos

Reputation: 68738

You can wrap an inline function:

namespace A
{
    template<typename T, typename U>
    void f(T a, U b);
};

namespace B
{
    inline void f(int a, double b) { A::f(a,b); }
};

See this question:

C++11: How to alias a function?

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 477640

You can use using:

namespace A {
    template <typename T> void f(T);
    template <> void f<int>(int);    // specialization
}

namespace B {
    using ::A::f;
}

You can't distinguish between the specializations like that (since using is only about names), but it should be enough to make the desired specialization visible.

Upvotes: 5

Related Questions