0

I'm trying to specialize a static template function from a base class, and figured this was a good use case for a typedef/using statement. I can't seem to get it to work, though. Is this illegal, or is my syntax wrong?

#include <iostream>

class Base {
public:
    template <typename T>
    static T func () {
        std::cout << (T)3.145 << std::endl;
    }
};

class Derived : public Base {
public:
//  using derivedFunc = Base::func<int>; // This doesn't work
//  typedef Base::func<int> derivedFunc; // Nor this
    static constexpr auto derivedFunc = &Base::func<int>; // But this seems to work
};

int main() {
    Base::func<double>(); // Prints 3.145
    Derived::derivedFunc(); // Prints 3
    return 0;
}

1 Answers1

0

The using or typedef expect a type to create a type alias, but you are passing a value, namely a pointer to a function. The last line which works does exactly that: The auto is deduced to a pointer which is assigned the pointer to the function. It becomes more explicit if you write it without auto:

static constexpr int(*derivedFunc)() = &Base::func<int>;

Or if you use this:

using derivedFuncType = decltype(&Base::func<int>);
static constexpr derivedFuncType derivedFunc = &Base::func<int>;

which in the first line shows how to get the required type from the function pointer and use the type alias to define the actual member variable from it.

Live example

In all cases, you now have a function pointer. The pointer itself is static, hence the pointer can be accessed with Derived::derivedFunc and it can be called with Derived::derivedFunc().

Daniel Frey
  • 55,810
  • 13
  • 122
  • 180
  • Ah, I somehow thought C++ allowed alias declarations of template functions the same way as template classes. But obviously they are different things. Static pointer it is, then. –  Jul 10 '15 at 11:15