gpt4 book ai didi

c++ - 如何创建 C++ 模板以最佳方式传递值?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:05:03 24 4
gpt4 key购买 nike

我似乎记得我使用类型的大小来选择参数的值传递或引用传递的方法。

类似于:

void fun( check<A> a ){
...
}

生成或:

void fun( A a ){
...
}

void fun( A & a ){
...
}

取决于类型 A 的大小和您编译应用程序的架构。

最佳答案

在 C++11 中你可以使用 std::conditional :

#include <type_traits>

class A { ... };

typedef std::conditional<
std::is_trivially_copyable<A>::value && sizeof(A) <= sizeof(int),
A, const A&>::type AParam;

// Direct usage
void f(AParam param);

// Wrap into template class
template <typename T> struct check:
std::conditional<std::is_arithmetic<T>::value, T, const T&> {};

void f(check<A>::type param);

对于 C++03 编译器,您可以使用 Boost 实现 - Boost.TypeTraits library .

正如@sehe 提到的,还有 Boost.CallTraits library正确实现所需功能的:

#include <boost/call_traits.hpp>

class A { ... };

void f(boost::call_traits<A>::param_type param);

关于c++ - 如何创建 C++ 模板以最佳方式传递值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12752220/

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