c – 使用SFINAE禁用模板类成员函数

是否可以使用SFINAE和std :: enable_if来禁用模板类的单个成员函数

我目前有一个类似于此的代码

#include <type_traits>
#include <iostream>
#include <cassert>
#include <string>

class Base {
public:
    virtual int f() { return 0; }
};

template<typename T>
class Derived : public Base {
private:
    T getValue_() { return T(); }

public:
    int f() override {
        assert((std::is_same<T,int>::value));
        T val = getValue_();
        //return val; --> not possible if T not convertible to int
        return *reinterpret_cast<int*>(&val);
    }
};


template<typename T>
class MoreDerived : public Derived<T> {
public:
    int f() override { return 2; }
};


int main() {
    Derived<int> i;
    MoreDerived<std::string> f;
    std::cout << f.f() << " " << i.f() << std::endl;
}

理想情况下,如果T!= int,则应禁用Derived< T> :: f().因为f是虚拟的,所以Derived< T> :: f()会为Derived的任何实例化生成,即使它从未被调用过.
但是使用代码使得Derived< T> (使用T!= int)永远不会仅作为MoreDerived< T>的基类创建.

所以Derived< T> :: f()中的hack是编译程序所必需的; reinterpret_cast行永远不会被执行.

解决方法

你可以简单地将f专门化为int:
template<typename T>
class Derived : public Base {
private:
    T getValue_() { return T(); }

public:
    int f() override {
        return Base::f();
    }
};

template <>
int Derived<int>::f () {
    return getValue_();
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...