特化基类class的静态模板函数

Specialize static template function of base class

我正在尝试从基础 class 中专门化静态模板函数,并认为这是 typedef/using 语句的一个很好的用例。不过,我似乎无法让它发挥作用。这是非法的,还是我的语法错误?

#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;
}

usingtypedef 期望类型创建类型别名,但您传递的是一个值,即指向函数的指针。有效的最后一行正是这样做的: auto 被推导为一个指针,该指针被分配给函数的指针。如果你写 without auto:

会变得更明确
static constexpr int(*derivedFunc)() = &Base::func<int>;

或者如果你使用这个:

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

第一行显示了如何从函数指针中获取所需的类型,并使用类型别名从中定义实际的成员变量。

Live example

在所有情况下,您现在都有一个函数指针。指针本身是 static,因此可以使用 Derived::derivedFunc 访问指针,并且可以 调用 使用 Derived::derivedFunc().