English 中文(简体)
C++模板:字节/引用相互干扰
原标题:C++ Templates: Byval/Reference interfering with eachother

这是我问题的简化版本。我有一个财产类。它有has_initalized之类的数据,我在这个例子中删除了这些数据。

当我调用一个使用T的函数时,它很好。然而,T&;不是吗?所以我决定写一篇T&;但这会导致所有使用纯T的函数都出现编译错误。为什么T&;干扰?对于这个例子,我如何在不更改main()的情况下让两个函数(Q和W)都工作?

template <class T>
class Property {
    T v;
    Property(Property&p) { }
public:
    Property() {}
    T operator=(T src) { v = src; return v; }
    operator T() const { return v; }
    operator T&() const{ return v; }
    T operator->() { return v; }
};

class A{};

void Q(A  s){}
void W(A& s){}

int main(){
    Property<A> a;
    Q(a);
    W(a);
}
最佳回答

C++的重载规则中没有允许编译器在运算符T()操作符T&;()在对Q的调用中。因此,删除

operator T() const { return v; }

也将消除歧义。但是,您会遇到一个问题,因为不可能在const函数中返回对成员的非const引用。

问题回答

对于Q,您可以同时使用这两个转换函数。您可以通过使一个非常数使编译器更喜欢一个而不是另一个。

operator T() const { return v; }
operator T&() { return v; }

现在对于Q运算符T&。这种方式还将修复对W的调用,以获得一个非常数引用。您也可以从其他

operator T const&() const { return v; }
operator T&() { return v; }

这种方式仍然更喜欢Q的第二个转换函数,但如果您的对象a是const,并且您初始化了const引用,则不总是需要复制v





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?