2014-03-05 137 views
1

我有以下代码:c + +返回类型和类型名称

#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; 
} 

这使此错误在VS2012:error C3892: 'd' : you cannot assign to a variable that is const

我可以通过限定第一功能返回类型(如在评论修复它大纲)。但我真的不明白这里发生了什么。这是一个编译器错误还是真正危险的代码?

+2

您必须符合'::',因为您有一个与该类型名称相同的函数。 – Adam

+0

@亚当是的。我想我只是感到惊讶,编译器找到函数名并在类型名到达返回类型之前隐藏它。 – user673679

回答

3

clang给出了一个更友好的警告:

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不起作用,因此您必须使用范围解析运算符。