加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:20:40 所属栏目:百科 来源:网络整理
导读:是否可以使用SFINAE和std :: enable_if来禁用模板类的单个成员函数? 我目前有一个类似于此的代码: #include type_traits#include iostream#include cassert#include stringclass Base {public: virtual int f() { return 0; }};templatetypename Tclass De
是否可以使用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_();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读