【问题标题】:Specialize static template function of base class特化基类的静态模板函数
【发布时间】:2015-07-09 18:43:00
【问题描述】:

我正在尝试从基类中专门化一个静态模板函数,并认为这是 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;
}

【问题讨论】:

    标签: templates c++11 static typedef template-specialization


    【解决方案1】:

    usingtypedef 期望一个类型来创建一个类型别名,但您传递的是一个值,即指向函数的指针。起作用的最后一行正是这样做的:auto 被推导出为一个指针,该指针被分配了指向函数的指针。如果你写它会变得更加明确没有 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()调用

    【讨论】:

    • 啊,我不知何故认为 C++ 允许模板函数的别名声明与模板类的方式相同。但显然它们是不同的东西。那么它就是静态指针。
    猜你喜欢
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多