gpt4 book ai didi

c++ - 依赖型自动扣除

转载 作者:行者123 更新时间:2023-11-30 01:07:30 24 4
gpt4 key购买 nike

是否可以这样做:

template<class T, T type>
constexpr auto f(/* type used in some way... */) // -> decltype (etc. in case of C++11)
{
return std::integral_constant<T,t>{};
}

constexpr auto z = f(3); // z is deduced as an integral_constant<int,3>;

肯定不可能使用运行时值,但在这种情况下 3 是编译时值。也许有人知道一些我不知道的把戏......

[编辑] constexpr auto z2 = f<3>();//这样也行

我只是想避免重复类型..

最佳答案

您可以在 C++17 中使用 auto 模板参数:

template <auto T>
constexpr auto f()
{
return std::integral_constant<decltype(T), T>{};
}

用法:

f<3>(); // integral_constant<int, 3>

或者,您需要以编译时友好的方式包装您的值:

template <int X>
struct int_
{
using type = int;
static constexpr value = X;
};

template <typename T>
constexpr auto f(T)
{
return std::integral_constant<typename T::type, T::value>{};
}

用法:

f(int_<3>{});

关于c++ - 依赖型自动扣除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44415152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com