gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:26:14 26 4
gpt4 key购买 nike

是否可以使用 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;
}

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

所以 Derived<T>::f() 中的黑客是使程序编译所必需的; 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++ - 使用 SFINAE 禁用模板类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38635776/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com