我一直在尝试使用带有以下形式代码的模板进行类型推导/打印:
#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/