【问题标题】:Generating a new type at every instantiation in C++17在 C++17 中的每次实例化时生成一个新类型
【发布时间】:2017-07-21 23:16:38
【问题描述】:

考虑以下代码:

template <class /* Weird Hack Here */>
struct object
{
    constexpr object(int value, /* Other Weird Hack */) noexcept;
};

int main() 
{
    object foo(1);
    object bar(1);
}

是否有可能在 C++17 中使用奇怪的技巧使 foo 和 bar 成为不同的类型?

【问题讨论】:

  • 所以如果我将object x(1); 放入一个循环中,您是否期望不同类型的数量不限?
  • 由于stateful metaprogramming,可能会出现类似的情况,但将来会被禁止
  • 不是 C++17,但元类提案会为您提供强大的 typedef,它可以完成几乎相同的事情。

标签: c++ templates template-meta-programming constexpr c++17


【解决方案1】:

真正的答案:不。如果你想要不同的类型,就写不同的类型。整个概念很疯狂。


玩具答案,当然。一方面,您可以宏化类型:

template <int N>
struct object {
    object(int ) { }
};

#define object object<__LINE__>

或者,因为我们太厚脸皮了,你可以将foo 和bar 这两个名字都宏化出来:

template <int N>
struct object {
    object(int ) { }
};

#define foo(x) <0> foo(x)
#define bar(x) <1> bar(x)

或者,也许只是其中之一:

template <class T>
struct object {
    object(T ) { }
};

#define foo(x) <double> foo(x)

或者,您可以使用stateful metaprogramming 破解不同的值。这适用于gcc,但不适用于clang:

template <int N>
struct flag
{
    friend constexpr int adl_flag(flag<N>);
    constexpr operator int() { return N; }
};

template <int N>
struct write
{
    friend constexpr int adl_flag(flag<N>) { return N; }
    static constexpr int value = N;
};

template <int N, int = adl_flag(flag<N>{})>
constexpr int read(int, flag<N>, int R = read(0, flag<N + 1>{}))
{
    return R;
}

template <int N>
constexpr int read(float, flag<N>)
{
    return N;
}

template <class T, int N=0, int R=write<read(0, flag<0>{})+N>::value>
struct object {
    object(T ) { }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2021-08-05
    相关资源
    最近更新 更多