3

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

weggo
  • 134
  • 3
  • 10
  • After a glance, does this help? http://www2.research.att.com/~bs/C++0xFAQ.html#template-alias – chris Apr 09 '12 at 18:56
  • Not quite sure if it does, since it seems the current version of visual c++ doesn't support using syntax(?). At least for me it just outputted loads of syntax errors – weggo Apr 10 '12 at 07:03
  • The compiler has to support the feature as well. I don't think GCC does yet. – chris Apr 10 '12 at 11:22

2 Answers2

5

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
2

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?

Community
  • 1
  • 1
Andrew Tomazos
  • 66,139
  • 40
  • 186
  • 319