Can a variable template be passed as a template template argument?
Asked Answered
S

1

16

The following nonsensical example does not compile, but is there some other way to pass a variable template as a template template argument?

template<typename T>
constexpr auto zero = T{0};

template<typename T, template<typename> auto VariableTemplate>
constexpr auto add_one()
{
    return VariableTemplate<T> + T{1};
}

int main()
{
    return add_one<int, zero>();
}

Try on Compiler Explorer

Sulfur answered 28/10, 2019 at 14:0 Comment(0)
M
7

Short answer: No.

Long answer: Yes you can using some indirection through a class template:

template<typename T>
constexpr auto zero = T{0};

template<typename T>
struct zero_global {
    static constexpr auto value = zero<T>;
};

template<typename T, template<typename> class VariableTemplate>
constexpr auto add_one()
{
    return VariableTemplate<T>::value + T{1};
}

int main()
{
    return add_one<int, zero_global>();
}

Live example

Moorland answered 28/10, 2019 at 14:6 Comment(3)
seems a bit backwards that one has to resort to struct with static member. Is this something one can expect to come with a future standard? Any idea why it isnt possilble already today?Mylor
@formerlyknownas_463035818 I don't think anybody proposed it yet (never saw it in the paper, maybe I missed it?) And there is a complexity too. Right now, non-type template parameter are pr-values. But what would value<T> would mean? A reference to the global variable? Also, you can't ODR use non-type template parameter, but you can with a template global.Moorland
thanks for the hints, I am still on c++11, so I am not too familiar with variable templates, and thats something I would have expected to work out of the boxMylor

© 2022 - 2024 — McMap. All rights reserved.