【问题标题】:std::conditional for compile time inheritance paired with std::enable_if for compile time methodsstd::conditional 用于编译时继承与 std::enable_if 用于编译时方法
【发布时间】:2022-06-15 21:22:34
【问题描述】:

我想设计一个带有两个参数的模板类,这些参数在编译时基于两个互斥基类之一的模板参数继承。 我想对我来说保持简单,所以想出了这个工作示例。我基于模板参数使用std::conditional 获得的继承条件。我使用std::enable_if 设置的条件继承的专用方法。

class Empty {};

template<typename T>
class NonEmpty { protected: std::vector<T> mObjects; };

template< typename A, typename B = A>
class Storage : public std::conditional<std::is_same<A, B>::value, Empty, NonEmpty<B>>::type
{
 public:

    template<typename C = B, typename std::enable_if<std::is_same<C, A>::value>::type* = nullptr>
    void doStuff()
    { 
        // one argument or two arguments with same type 
        // do stuff ...
    };

    template<typename C = B, typename std::enable_if<std::is_same<C, A>::value>::type* = nullptr>
    void doSomthingElse()
    { 
        // one argument or two arguments with same type 
        // do something exclusively just for this argument constellation  ...
    };


    template<typename C = B, typename std::enable_if<!std::is_same<C, A>::value>::type* = nullptr>
    void doStuff()
    { 
        // two arguments with different types
        // do stuff with inherited variables of NonEmpty-Class ...
    };

};

int main()
{
   EmptyClass<int> emp;
   NonEmptyClass<int, float> nonemp;

   emp.doStuff();
   emp.doSomethingElse();
   nonemp.doStuff();
}

有没有更好的方法来解决这个问题,或者我现有的解决方案有什么改进? (我在 C++ 14 中使用 GCC 8.1.0)

【问题讨论】:

  • 部分专业化是一回事。

标签: c++ templates inheritance conditional-statements enable-if


【解决方案1】:

我没有看到将它们全部放在一个模板中的好处。我的印象是,您通过将所有内容都填充到一个模板中而使事情变得复杂,但随后需要为每个单独的方法选择哪个版本。两个单独的类:

template <typename A>
struct inherits_from_empty : Empty {
     // implement methods here, no sfinae needed
};

template <typename A>
struct inherits_from_nonEmpty : NonEmpty<A> {
    // implement methods here, no sfinae needed
};

可以从via中选择

template <typename A>
using Storage = std::optional_t< put condition here , inherits_from_empty<A>,inherits_from_nonEmpty<A>>;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    相关资源
    最近更新 更多