C++ C++;返回类型和类型名
我有以下代码:C++ C++;返回类型和类型名,c++,qualified-name,C++,Qualified Name,我有以下代码: #include <iostream> #include <tuple> struct H { static const int Index = 0; }; struct V { static const int Index = 1; }; struct Slice { Slice(): Value(5) { } int Value; }; class Dimension { public: templa
#include <iostream>
#include <tuple>
struct H
{
static const int Index = 0;
};
struct V
{
static const int Index = 1;
};
struct Slice
{
Slice(): Value(5) { }
int Value;
};
class Dimension
{
public:
template<class D>
Slice& Slice() // causes compiler error
//::Slice& Slice() // compiles ok
{
return std::get<D::Index>(slices);
}
template<class D>
::Slice const& Slice() const
{
return std::get<D::Index>(slices);
}
private:
typedef std::tuple<::Slice, ::Slice> SlicesT;
SlicesT slices;
};
int main(int, char*[])
{
Dimension d;
std::cout << d.Slice<V>().Value << std::endl;
d.Slice<V>().Value = 10; // error here
std::cout << d.Slice<V>().Value << std::endl;
}
#包括
#包括
结构H
{
静态常量int索引=0;
};
结构V
{
静态常数int指数=1;
};
结构切片
{
Slice():值(5){}
int值;
};
类维度
{
公众:
模板
Slice&Slice()//导致编译器错误
//::Slice&Slice()//编译正常
{
返回std::get(切片);
}
模板
::切片常量&切片()常量
{
返回std::get(切片);
}
私人:
typedef std::元组切片;
切片;
};
int main(int,char*[])
{
维度d;
std::coutclang
给出了更友好的警告:
main.cpp:33:5: error: must use 'struct' tag to refer to type 'Slice' in this scope
Slice const& Slice() const
^
struct
main.cpp:26:12: note: struct 'Slice' is hidden by a non-type declaration of 'Slice' here
Slice& Slice() // causes compiler error
^
1 error generated.
struct Slice
或::Slice
都可以让编译器知道您指的是类型。在MSVC上,由于某种原因,struct Slice
不起作用,因此必须使用范围解析运算符。您必须使用:
进行限定,因为您有一个与类型同名的函数。@Adam是的。我猜是这样的我只是惊讶于编译器在返回类型之前找到了函数名并隐藏了类型名。