我需要一种方法来决定是通过复制还是通过 const-reference 传递任意类型 T(例如,如果 T 足够小,则复制 if,否则通过 const-reference 传递它)。为了避免重新发明轮子,我尝试了 Boost Call Traits。
正如预期的那样,原始类型通过值传递,而复杂类型std::string
则通过引用传递。但是,微小的非原始类型也通过引用传递,例如 ,std::pair<char, char>
这似乎不是最佳选择。我假设所有内容都sizeof(void*)
将按值传递。
一般来说,Boost 库质量很高,所以也许我遗漏了一些东西。
这是我的测试代码:
#include <iostream>
#include <type_traits>
#include <tuple>
#include <boost/call_traits.hpp>
template <typename TYPE>
void test(const char* type_name)
{
typedef typename boost::call_traits<TYPE>::param_type T;
if(std::is_reference<T>::value)
std::cout << type_name << " is passed by reference (sizeof=" << sizeof(TYPE) << ")\n";
else
std::cout << type_name << " is passed by value (sizeof=" << sizeof(TYPE) << ")\n";
}
int main()
{
test<short>("short");
test<int>("int");
test<double>("double");
test<std::string>("std::string");
test<long long>("long long");
test<std::pair<int, int>>("std::pair<int, int>");
test<std::pair<short, short>>("std::pair<short, short>");
test<std::pair<char, char>>("std::pair<char, char>");
test<std::tuple<char, char>>("std::tuple<char, char>");
test<std::tuple<char, char, char, char>>("std::tuple<char, char, char, char>");
test<std::pair<long long, long long>>("std::pair<long long, long long>");
return 0;
}
以下是结果(Boost 1.50,g++ 4.7.2):
short is passed by value (sizeof=2)
int is passed by value (sizeof=4)
double is passed by value (sizeof=8)
std::string is passed by reference (sizeof=8)
long long is passed by value (sizeof=8)
std::pair<int, int> is passed by reference (sizeof=8)
std::pair<short, short> is passed by reference (sizeof=4)
std::pair<char, char> is passed by reference (sizeof=2)
std::tuple<char, char> is passed by reference (sizeof=2)
std::tuple<char, char, char, char> is passed by reference (sizeof=4)
std::pair<long long, long long> is passed by reference (sizeof=16)