繁体   English   中英

推导功能模板参数的确切类型

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM