簡體   English   中英

非類型模板參數

[英]Non type template parameter

考慮一下:

#include <set>

template <typename T, T val>
class sample {
public:
    // Return val for new elements.
    T& at(unsigned i) {
       auto o = _set.insert(val);
       return *o.first;
    }

private:
    std::set<T> _set;
};

class s {
public:
    constexpr s() = default;
};


int main() {
    constexpr s val;
    sample<s, val> o2;
    return 0;
}

gcc -std=c++11 不能編譯。

non-type.cc: In function ‘int main()’:
non-type.cc:24:18: error: ‘class s’ is not a valid type for a template non-type parameter
     sample<s, val> o2;

如評論中所述,我希望將“set”的新元素初始化為“val”。 由於 val 是常數,它看起來是合理的期望!

有人可以告訴我如何實現它嗎?

看起來您想要做的事情是可能的,但需要 C++20。

文檔

在 C++20 之前,“非類型參數”需要是其中之一

- std::nullptr_t (since C++11); - an integral type; - a pointer type (to object or to function); - a pointer to member type (to member object or to member function); - an enumeration type.

除非您可以訪問已經具有該功能的編譯器,否則目前似乎無法使用自定義類型的非類型參數。

您的示例中的解決方法是接受參考。 即使在 C++11 中,對靜態對象的引用也是有效的非類型模板參數。

template <typename T, T const & val>
class sample {
    // ...
};

// ...

constexpr static s val;
sample<s, val> o2;

由於您打算使用constexpr val,因此將其設為static似乎也很合適。

暫無
暫無

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

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