Can a variable template be passed as a template template argument?

☆樱花仙子☆ 提交于 2020-05-23 04:20:42

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/58592312/can-a-variable-template-be-passed-as-a-template-template-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!