【问题标题】:Generate new type whenever function called in C++每当在 C++ 中调用函数时生成新类型
【发布时间】:2017-02-13 03:02:20
【问题描述】:

是否可以在调用函数时生成新类型? 我读过每个 lambda 都有自己独特的类型,所以我尝试过:

template<class T, class F> struct Tag { };
template<class T>
auto func(const T &t) -> auto
{
    auto f = [] () {};
    return Tag<T, decltype(f)>();
}
static_assert(!std::is_same_v<decltype(func(0)), decltype(func(1))>, "type should be different.");

但是,static_assert 失败了。

无论T 的类型和t 的值如何,我可以让func() 在调用func() 时返回不同类型的值吗?

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    不,不是在调用函数时。类型是在编译时生成的,而不是在运行时生成的。

    查看问题Can the 'type' of a lambda expression be expressed? 这是基于那里的答案的代码。

    #include <iostream>
    #include <set>
    
    int main()
    {
      auto n = [](int l, int r) { return l > r; };
      auto m = [](int l, int r) { return l > r; };
      std::set<int, decltype(n)> s(n);
      std::set<int, decltype(m)> ss(m);
      std::set<int, decltype(m)> sss(m);
    
      std::cout << (std::is_same<decltype(s), decltype(ss)>::value ? "same" : "different") << '\n';
      std::cout << (std::is_same<decltype(ss), decltype(sss)>::value ? "same" : "different") << '\n';
    
    }
    

    结果:

    different
    same
    

    【讨论】:

      【解决方案2】:

      C++是一种静态类型语言,这意味着类型只存在于源代码中,在运行时几乎没有留下任何痕迹。 Lambda 也不例外——它们确实有独特的类型,但它们是在编译时定义的。

      模板确实可以用来生成新类型,这是可能的,因为模板是在编译时评估的,因此也只存在于源代码中。
      所以严格的答案是否定的,当函数被调用时,你不能生成新的类型,因为函数调用发生在运行时。

      话虽如此,您可以通过一些巧妙的设计在 C++ 中实现几乎任何理想的灵活性,只需查看一些常见的设计模式。

      【讨论】:

        猜你喜欢
        • 2013-12-27
        • 1970-01-01
        • 2015-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-02
        • 1970-01-01
        • 2023-03-11
        相关资源
        最近更新 更多