【问题标题】:Definition of pure virtual method while using templated class with sfinae使用带有 sfinae 的模板类时纯虚方法的定义
【发布时间】:2021-05-24 16:44:21
【问题描述】:

我正在尝试学习和使用 sfinae,这是我第一次尝试这样做。我有以下代码:

template<class CoreType, typename std::enable_if_t<std::is_base_of_v<Core, CoreType>>* = nullptr>
class Window
{
protected:
    std::shared_ptr<Engine<CoreType>> _engine;
public:
    virtual ~Window() = 0;
};

template<class CoreType, typename std::enable_if_t<std::is_base_of_v<Core, CoreType>>* = nullptr>
Window<CoreType>::~Window() {} // <- problem is here

我收到此错误:E0498 模板参数列表必须与参数列表匹配

似乎我应该以某种方式提供 sfinae 的虚拟参数,但如何提供?

如果我删除导致问题的, typename std::enable_if_t&lt;std::is_base_of_v&lt;Core, CoreType&gt;&gt;* = nullptr,它会正常工作,但我想学习如何使用 sfinae,我只能在 google 上找到这个特殊情况。任何人都可以帮我解决这个问题吗?谢谢

【问题讨论】:

标签: c++ templates visual-c++ template-meta-programming sfinae


【解决方案1】:

您告诉编译器~Window () 函数是Window&lt;CoreType&gt; 类的一部分。但是,没有这样的课程。您定义的类有两个模板参数(一个用于 SFINAE 的事实并不重要)。

您也在使用typename std::enable_if_t&lt;...&gt;,但_t 后缀表示typename 已为您完成。所以你有typename typename std::enable_if&lt;...&gt; 在那里。

还请注意,您不应重复默认模板参数,就像您不应为函数定义重复默认函数参数一样。

最后,您必须为所有参数命名,以便能够引用它们。所以未命名的std::enable_if_t 需要一个名字。

所有这些一起变成:

template <class CoreType,
    std::enable_if_t<std::is_base_of_v<Core, CoreType>> * Enable>
Window<CoreType, Enable>::~Window() {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 2019-01-01
    • 2016-10-14
    • 1970-01-01
    • 2012-02-13
    • 2020-08-09
    • 1970-01-01
    相关资源
    最近更新 更多