eXXXXXXXXXXX2
eXXXXXXXXXXX2

Reputation: 1580

Type and non-type template parameters to use interchangeably

Is it possible in C++ to declare some class so that it would be allowed to pass integer value or type as template parameter?

Something like this:

#include <iostream>
using namespace std;

template <auto I>
struct Foo {};

int main()
{
    Foo<int> foo1;
    Foo<1> foo2;
    return 0;
}

Upvotes: 2

Views: 74

Answers (1)

Vittorio Romeo
Vittorio Romeo

Reputation: 93264

Nope, that is not possible. As a workaround, you could use std::integral_constant in order to pass values homogeneously as types.

template <typename I>
struct Foo {};

int main()
{
    Foo<int> foo1;
    Foo<std::integral_constant<int, 1>> foo2;
}

With C++17, you can define

template <auto I>
using constant = std::integral_constant<decltype(I), I>;

to avoid some boilerplate.

Upvotes: 6

Related Questions