非类型模板参数

时间:2019-12-30 08:14:34

标签: c++ templates non-type

考虑一下:

#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是常数,因此看起来是合理的期望值!

有人可以告诉我如何实现吗?

2 个答案:

答案 0 :(得分:6)

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

docs

在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.

除非您可以访问已经具有该功能的编译器,否则目前似乎无法使用具有自定义类型的非类型参数。

答案 1 :(得分:0)

您的示例中的一种解决方法是接受参考。即使在C ++ 11中,对静态对象的引用也是有效的非类型模板参数。

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

// ...

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

由于您打算使用constexpr值,因此将其设置为static也很合适。