2015-09-27 50 views
2

您好下面的程序可與G ++ 4.9.2(Ubuntu的4.9.2-10ubuntu13),但是是所必需的功能的get關鍵字virtual虛擬關鍵字:從constexpr函數返回一個類需要使用g ++

//g++ -std=c++14 test.cpp 
//test.cpp 

#include <iostream> 
using namespace std; 

template<typename T> 
constexpr auto create() { 
    class test { 
    public: 
    int i; 
    virtual int get(){ 
     return 123; 
    } 
    } r; 
    return r; 
} 

auto v = create<int>(); 

int main(void){ 
    cout<<v.get()<<endl; 
} 

如果我省略了virtual關鍵字,我得到以下錯誤:

test.cpp: In instantiation of ‘constexpr auto create() [with T = int]’: 
test.cpp:18:22: required from here 
test.cpp:16:1: error: body of constexpr function ‘constexpr auto create() [with T = int]’ not a return-statement 
} 
^ 

我怎樣才能得到上面的代碼,而不必使用virtual關鍵字(使用g ++)工作?

+1

程序編譯細帶有[最新版本克++的](http://melpon.org/wandbox/permlink/MYiV0wciN8hWmhAM)。輕鬆的C++ 14 constexpr函數規則在gcc> = 5中實現,請參閱https://gcc.gnu.org/projects/cxx1y.html在此之前,您無法在constexpr函數中聲明類。 'get'是'虛擬'時缺少診斷是誤導性的。 – dyp

回答

0

函數內定義的類不能在函數外部訪問。 我的建議是:在功能外聲明test並將const限定符添加到get函數。

#include <iostream> 
using namespace std; 

    class test { 
    public: 
    int i; 
    int get() const { 
     return 123; 
    } 
    }; 

template<typename T> 
constexpr test create() { 
    return test(); 
} 

auto v = create<int>(); 

int main(void){ 
    cout<<v.get()<<endl; 
} 
+0

謝謝,但不幸的是,這不是我想爲我的特定工作案例做事情的方式。 – artella

+0

*「在函數內部定義的類不能在函數外部訪問。」*這是不正確的,因爲C++ 14的返回類型推導(或C++ 11對lambda表達式的寬鬆返回類型推導)。 – dyp

+0

@Andrey Nasonov請參閱http://stackoverflow.com/questions/32806835/how-to-specify-type-of-a-constexpr-function-returning-a-class-without-resorting?noredirect=1#comment53450804_32806835更詳細的解釋我想要達到的目標。 – artella

相關問題