簡體   English   中英

如何返回對非類型模板參數的默認值的引用

[英]how to return a reference to a default value of a non-type template argument

我對此進行了大量研究,但找不到解決該問題的設計模式。 這是對我要執行的操作的簡要說明。

#include <iostream>
using namespace std;

template <class T, T default_value=T{}>
class A{
private:
       T inclassValue;
public:
       A(T icv):inclassValue{icv}{}       

       const T& operator[](int k){
          if(k==1) return inclassValue;
       return default_value; 
       }
};

struct two_int{int x;int y;};

int main(){
    A<int> a{4};
    cout << "a[0]=" << a[0] << endl;
    cout << "a[1]=" << a[1] << endl;
    /*
    A<two_int> b{{3,5}};
    cout << "b[0]=" << b[0].x << "," << b[0].y  << endl;
    cout << "b[1]=" << b[1].x << "," << b[1].y  << endl;
    */
    return 0;

}

該代碼將按預期進行編譯,鏈接和輸出

a[0]=0
a[1]=4

但是,編譯器會抱怨並針對使用default_value的代碼行發出警告

return default_value;//Returning reference to local temporary object

這很有道理。 取消注釋main和compilation的最后部分,編譯器這次在構建模板時發出錯誤

template <class T,  const T default_value= T{}>//A non-type template parameter cannot have type 'two_int'

而我理想中希望的是

b[0]=0,0
b[1]=3,5

通過添加一個額外的幫助程序類,我可以提供一個解決方案,該類將為模板參數提供T的default_value(作為靜態成員)。 我不相信我的技巧的魯棒性,我想知道是否存在解決此問題的設計模式。 類型的警告和非類型的錯誤。 另外,我還要補充一點,我的主要目標是能夠隨意提供default_value(例如,對於int為6而不是0)。

謝謝

不確定所要查找的內容,但也許可以使用用於創建靜態默認T的靜態幫助程序完成工作:

template <typename T>
static const T& default_value() {
  static const T* t = new T{};
  return *t;
}

請注意,即使在線程之間(在c ++ 11中),它最多也可以構造T,但仍然永遠不會破壞T。由於它是靜態的,可能缺少破壞是可以接受的,但這當然取決於T。

這是一個將參數轉發到存儲為constexpr的default_value的構造函數的版本。 在這里,您可以有效地傳遞什么參數作為參數非常有限(不確定到底有多有限),所以這將取決於您的用例。

#include <iostream>
using namespace std;

template <class T, auto... Args>
class A{
private:
       T inclassValue;
       constexpr static T default_val = T{Args...}; // Changed to curly brackets here
public:
       constexpr A(T icv):inclassValue{icv}{}       

       const T& operator[](int k){
          if(k==1) return inclassValue;
       return default_val; 
       }
};

struct two_int{int x;int y;};

int main(){
    A<int> a{4};
    cout << "a[0]=" << a[0] << endl;
    cout << "a[1]=" << a[1] << endl;

    A<two_int> b{{3,5}};
    cout << "b[0]=" << b[0].x << "," << b[0].y  << endl;
    cout << "b[1]=" << b[1].x << "," << b[1].y  << endl;

    return 0;
}

暫無
暫無

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

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