Search code examples
c++templatesnon-type

Non type template parameter


Consider this:

#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 doesn't compile.

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;

As mentioned in the comment, I want new elements of 'set' are initialized to 'val'. As val is constant, it looks reasonable expectation!

Can someone please tell me how I can achieve it?


Solution

  • It looks like what you want to do is possible, but requires C++20.

    From the docs

    Until C++20 a "non-type parameter" needs to be one of

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

    Having a non-type parameter of a custom type seems to not be available at the moment unless you have access to a compiler that already has that feature.