【问题标题】:Is there a way to store compile time constant in a class instance?有没有办法将编译时间常量存储在类实例中?
【发布时间】:2018-11-26 23:12:41
【问题描述】:

我试图看看我是否可以创建一个在其生命周期中只能包含几种类型之一的异构类型(两种模式),我想这样做:

//strong typed (heterogeneous) container
template<typename list>
struct STC
{
    template<typename a>
    STC(const a& value) :hc_(value), index_(TMP::elem_index<a, list>::value) {}

    template<typename a>
    STC(a&& value) : hc_(value), index_(TMP::elem_index<a, list>::value) {}

    //imaginary compile time const
    constexpr size_t index()const { return index_; }

    typename TMP::index<list,index()>::type get() { return c_.get<index()>(); } 

    operator typename TMP::index<list,index()>::type ()const { return get(); }

private:
    union_magic<list> c_;
    const size_t index_;
};

其中 typename list 是模板元类型列表,TMP::elem_index 是用于检索列表元素索引的模板元函数,TMP::index 是用于检索具有已知索引的元素的元函数。

在我看来,没有办法跨越类数据成员和编译时间常数之间的界限。我错过了什么吗?这是错误的方法吗?或者这只是c++中不可能做到的事情,必须在运行时解决?

至于容器如何使用:

    void call_with(char c)
    {
        std::cout << "calling function with char type: " << c << std::endl;
    }

    void call_with(int i)
    {
        std::cout << "calling function with int type: " << i<< std::endl;
    }

    int main()
    {        
    STC<Cons<int, Cons<char, Nil>>> value(1);
    call_with(value);
    }

应该显示“调用 int 类型的函数:1”。

【问题讨论】:

  • 你能举一个这个类模板的编译时应用的例子吗?即,它将以何种方式使用以使其需要编译时间?
  • lista 类型元素的列表,否则编译时错误? IE。你能把list描述成std::vector&lt;a&gt;吗?
  • 你能显示一个代码sn-p吗?这确实有助于使问题更清晰。
  • 我想看看你将如何使用你想存储在STC中的编译时间常数。
  • 你的例子是不可能的。 STC&lt;Cons&lt;int, Cons&lt;char, Nil&gt;&gt;&gt; 类型的所有对象都将导致调用相同的重载。重载解析只考虑类型。

标签: c++ templates template-meta-programming compile-time compile-time-constant


【解决方案1】:

以下两个答案的组合是否有助于获得您想要的东西?

building and accessing a list of types at compile time

How can I get the index of a type in a variadic class template?

顺便说一句,将编译时元类型存储在index_ 中没有用处,它已分配并且只能在运行时使用。您可能会将其定义为 static constexpr size_t kIndex

【讨论】:

  • 但是它不再是实例字段,为了初始化静态 constexpr,我必须在其类型名称中包含该值,这是我试图避免的。如果运行时可以完成这项工作,那么追求更复杂的类型是没有意义的,我想我在问有没有办法在编译时没有复杂类型的情况下做更多事情。顺便说一句,我很擅长编译时列表,因为我熟悉 Haskell。
  • 您介意详细说明一下编译时/运行时分配,以便我可以让您的答案被接受吗?
  • @YunshengGuo const size_t index_;struct STC 的每个实例声明一个数据成员。它在运行时分配和初始化。您将无法“使用”它作为编译时参数(我之前说错了——您可以在其中存储编译时常量;但只能使用 它在运行时)。这意味着,与其做constexpr size_t index()const { return index_; },不如做static constexpr size_t kIndex = TMP::elem_index&lt;a, list&gt;::value之类的事情可能更直接?
  • 这是我使用实例的意图,因为我想要静态多态行为而不需要静态转换,现在我开始意识到这在 c++ 中是不可能的。
猜你喜欢
  • 2014-02-10
  • 1970-01-01
  • 2020-09-04
  • 2020-05-08
  • 2010-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多