[英]Deduce exact type of function template parameter
在下面的代碼中,將類型推斷規則用於模板參數(此問題與C ++ 14有關):
#include <iostream>
template <typename T>
void test(T x)
{
std::cout << "T x" << std::endl;
}
template <>
void test<int>(int x)
{
std::cout << "int x" << std::endl;
}
template <>
void test<int &>(int &x)
{
std::cout << "int &x" << std::endl;
}
int main()
{
int x = 5;
int &y = x;
test(x);
test(y);
return 0;
}
規則明確指出引用被丟棄( 例如,在此處進行了說明 ),因此輸出
int x
int x
非常期望將其作為最佳匹配過載。 但是在某些情況下,輸出為
int x
int &x
可能是可取的。 模板參數類型推導有沒有一種方法可以直觀地推斷出參數的確切類型?
您必須傳遞參數的十進制類型。 使用此宏可以克服語法上的障礙:
namespace detail{
template <typename T> void test(T){std::cout << "T" << std::endl;}
template <> void test<>(int){std::cout << "int" << std::endl;}
template <> void test<>(int&){std::cout << "int&" << std::endl;}
}
#define TEST(x) detail::test<decltype(x)>(x)
現在只需調用參數即可:
TEST(x) // int
TEST(y) // int&
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.