gpt4 book ai didi

c++ - 将值传递给功能模板的最佳方法

转载 作者:行者123 更新时间:2023-12-02 10:31:06 25 4
gpt4 key购买 nike

我正在编写一个接受模板类型的(常量)值的函数模​​板。移动语义不适用于我的情况。我应该如何传递参数?对于已知类型,决策大致为:

  • 小:按常量值
  • large:通过const引用

  • 但是对于作为模板参数的类型该怎么办?我能想到的最好的方法是使用一个模板,该模板的计算结果为 const Tconst T &,具体取决于 T的大小与指针的大小。
    // when no exact match: pass as a 1 byte smaller data type would be passed
    template< int N, typename T >
    struct _by_const { using type = _by_const< N - 1, T >::type; };

    // when up to the size of a pointer: pass by value
    template< typename T >
    struct _by_const< 1, T > { using type = const T; };

    // when larger than a pointer: pass by reference
    template< typename T >
    struct _by_const< 1 + sizeof( int * ), T > { using type = const T &; };

    // interface: use by_const< T > when passing a T
    template< typename T >
    using by_const = _by_const< sizeof( T ), T >::type;

    用法:
    template< typename T > void foo( by_const< T > p ){ ... }

    你怎么做到这一点?我错过了一个明显的解决方案吗?

    最佳答案

    好吧,如果大小很重要,

    template<class T> using arg_t = std::conditional_t<(sizeof(T) > sizeof(int *)), T const &, T>;

    但是请记住,单单在这里并不是很重要。 STL的容器作为对象可能很小(例如,一个指向缓冲区的指针,再加上其大小),但是它们处理堆上的大量资源,这就是它们无法复制的原因。您应该在谓词中添加类似std::is_trivial的内容,以增强信心。

    关于c++ - 将值传递给功能模板的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62260225/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com