簡體   English   中英

如何指定返回類的 constexpr 函數的類型(不使用 auto 關鍵字)

[英]How to specify type of a constexpr function returning a class (without resorting to auto keyword)

基本上在下面我想看看我是否可以繞過必須使用auto關鍵字

假設我們有以下代碼段[適用於 g++ 4.9.2 (Ubuntu 4.9.2-10ubuntu13) & clang version 3.6.0]:

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

如何指定v的類型而不是在其聲明/定義點使用auto關鍵字? 我試過create<int>::test v = create<int>(); 但這不起作用。

ps

1)這與我在Returning a class from a constexpr function requires virtual keyword with g++中提出的問題不同,即使代碼相同

2)我不想定義函數外的類。

實際類型是隱藏的,因為它在函數內部是局部的,因此您不能顯式使用它。 但是,您應該能夠像這樣使用decltype

decltype(create<int>()) v = create<int>();

但是,當auto工作時,我看不到這樣做的理由。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM