c++ - 引用模板类型推导

标签 c++ templates c++11

我一直在尝试使用带有以下形式代码的模板进行类型推导/打印:

#include <iostream>
template <typename T>
class printType {};

template <typename T>
std::ostream& operator<<(std::ostream& os, const printType<T>&)
{
    os << "SomeType"; return os;
}  

template <typename T>
std::ostream& operator<<(std::ostream& os, const printType<T*>&)
{
    os << printType<T>() << "*"; return os;
}  

template <typename T>
std::ostream& operator<<(std::ostream& os, const printType<T&>&)
{
    os << printType<T>() << "&"; return os;
}  
// etc... and can call on a variable through

template <typename T>
printType<T> print(T) { return printType<T>(); }  

int main()
{
    int a = 7;
    int *p = &a;
    int &r = a;

    //OK: return SomeType*
    std::cout << "type of p: " << print(p) << std::endl;
    //Hmmmm: returns SomeType <- (no &: can I get around this?)
    std::cout << "type of r: " << print(r) << std::endl;
}

我想知道我是否可以获得最后一行返回 int& ,即:
(i) 让函数模板 print 推断出它的参数类型为 int&或者以某种方式计算出它应该返回 printType<T&>当我通过它时;或者
(ii) 这是否由于变量传递给函数的方式而不可避免。

是否有任何方法可以通过更改打印形式或使用其他模板技巧来解决这个问题?如果存在解决方案,我更喜欢非 C++0x,但总是很高兴看到将来有哪些捷径(如果还没有的话)可用。

最佳答案

没有办法解决这个问题。表达式 p,其中 p 命名一个引用,始终具有引用所指的类型。没有表达式具有 T& 类型。因此,您无法检测表达式是否源自引用。

这也不能用 C++0x 来完成。没有表达式具有引用类型,这是 C++ 的一个深刻原则。您可以编写decltype(r) 来获取r 命名的类型,而不是表达式r 的类型有。但是你将无法编写 print(r),除非 print 当然是一个宏,但我不明白你为什么会走那条可怕的路。

关于c++ - 引用模板类型推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3786736/

相关文章:

c++ - 如何避免嵌套模板中的重复模板参数

c++ - 奇怪的未初始化 const 成员行为

c++ - CV - 自动变量的限定符

c++ - 为什么 c/c++ 浮点类型的命名如此奇怪?

c++ - 对 16 位灰度垫进行着色仅产生一半图像

c++ - 如何使用递归来反转用户输入?

c++ - boost_python with python 3.5 from anaconda - (few) undefined references

c++ - 结构和类层次结构(制作模板)

c# - 确定类是否在 T4 模板中实现泛型列表

c++ - 模板 'using' 声明不起作用