模板类型推导参考 [英] Template type deduction of reference

查看:48
本文介绍了模板类型推导参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been playing around with type deduction/printing using templates with code of the form:

#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& 或以某种方式计算出来的值,当我将其传递给r时,应返回 printType< T&> 。还是

(ii)是否由于变量传递给函数的方式而不可避免?

I am wondering whether or not I can get the last line to return int& , that is, either:
(i) have the function template print deduce the type of it's argument as int& or somehow work out it should return a printType<T&> when I pass it r; or
(ii)whether this is unavoidable because of the way the variable is passed to the function.

是否有任何方法可以通过更改印刷形式还是使用其他模板欺骗手段?如果存在解决方案,我宁愿使用非C ++ 0x,但总是很高兴看到将来会有哪些捷径(如果还没有的话)。

Are there any ways around this by changing the form of print or using some other template trickery? If solutions exists, I'd prefer non-C++0x, but is always good to see what short cuts will, if not already, be available in the future.

推荐答案

无法解决此问题。表达式 p (其中 p 命名引用)始终具有引用所引用的类型。没有任何表达式具有类型 T& 。因此,您无法检测到表达式是否源自引用。

There is no way to work this around. An expression p, where p names a reference, always has the type the reference refers to. No expression ever has type T&. So you cannot detect whether an expression originated from a reference or not.

这也不能用C ++ 0x完成。 C ++的一个深层原则是,没有具有引用类型的表达式。您可以 编写 decltype(r)来获取 r 名称的类型,而不是表达式 r 具有什么类型。但是除非 print 当然是宏,否则您将不能编写 print(r)没有看到为什么要走这条可怕的路。

This cannot be done with C++0x either. It's a deep principle of C++ that there are no expressions that have reference type. You can write decltype(r) to get the type of what r names instead of what type the expression r has. But you will not be able to write print(r), unless print is a macro of course, but I don't see why you would go that horrible road.

这篇关于模板类型推导参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆