Visual Studio与G++中的Decltype和friend函数
Decltype and friend functions in Visual Studio vs G++
我正在写一些C++代码来做向量数学。只需在std::array
实例周围使用一个薄薄的包装器就可以了。我想重载非成员begin()
函数,以便将迭代器返回到支持数组的开头。为此,我编写了一个简单的friend函数,该函数具有auto
返回类型和使用decltype
的尾随返回类型,该函数只是将调用转发到成员变量。
它无法编译,我也不明白为什么。我开始摆弄一个较小的例子,发现以下代码是在G++4.7下编译的,但不是在最新的VisualStudio2012Professional下编译的。
#include <iostream>
#include <array>
template <typename T, size_t size>
class MyClass {
private:
std::array<T, size> elts;
public:
friend auto begin(MyClass &a) -> decltype (std::begin(a.elts)) {
return std::begin(a.elts);
}
};
int main(void) {
MyClass<int, 8> instance;
auto it = begin(instance);
std::cout << *it << std::endl;
return 0;
}
奇怪的是,如果elts
的私有声明先于begin()
函数的声明,则此代码仅在G++中编译。
无论如何,哪一个编译器就在这里?Visual Studio还是G++?
编辑:VS2012给出的编译错误为error C2228: left of '.elts' must have class/struct/union
在使用表达式std::begin(a.elts)
时,类模板MyClass
的定义还不完整,所以我想VC有理由抱怨。不能在不完整的类型上使用operator .
。
在任何情况下,你都可以使用以下方法来解决这个问题:
#include <iostream>
#include <array>
template <typename T, size_t size>
class MyClass
{
// ...
friend typename std::array<T, size>::iterator begin(MyClass &a)
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
{
return std::begin(a.elts);
}
};
相关文章:
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在使用另一个类"friend"函数时无法发现错误C++
- 在运算符重载中使用带有 const 引用的 friend 函数
- 运算符重载(使用binaray friend函数)类没有成员,并且成员不可访问
- 类的 friend 函数无法访问其私有向量;
- 如何在 c++ 中使用常见的 Friend 函数
- 在Ostream Overload Friend函数中使用向量
- friend函数是如何在内部实现的
- Friend函数和未定义的私有方法
- c++ 派生基类 Friend 函数访问父级上的私有函数
- 前向声明的问题-Friend函数和行/点类
- 为什么friend函数不能访问类的私有成员
- 使用friend函数,我们可以覆盖类的私有成员吗
- Friend函数访问静态库中定义的类的私有成员
- 实现Friend函数
- Friend函数和命名空间.无法访问类中的私有成员
- 来自模板化类的Friend函数
- 使用Friend函数和operator+添加类变量并打印出来
- friend函数和include循环
- C++ Friend 函数位于单独的头文件和.cpp文件中