如何创建一个返回类型的constexpr函数(在模板参数中使用)

时间:2016-05-27 14:33:07

标签: c++

我正在寻找一些基于模板参数编号创建具有模板参数类型的类的方法。

我尝试做的事情是这样的:

template<size_t n>
constexpr auto type_from_size() {
    if(n < 256) {
        return uint8_t;
    } else {
        return uint16_t;
    }
}

template<size_t n>
class X {
    type_from_size<n>() t;
}

X<500> x;
x.t = 500;

因此,在上面的代码中,constexpr函数type_from_size()将收到数字500并返回类型uint16_t,这将是成员{{1}的类型}}

我知道这显然是可怕的代码,但这可能是使用模板吗?

4 个答案:

答案 0 :(得分:18)

函数无法返回类型。你应该使用一个模板。

仅在两种类型之间进行选择,built-in std::conditional就足够了。

#include <type_traits>
#include <cstdint>

template <size_t n>
using type_from_size = typename std::conditional<(n < 256), uint8_t, uint16_t>::type;
// ^ if `n < 256`, the ::type member will be typedef'ed to `uint8_t`.
//                 otherwise, it will alias to `uint16_t`.
//   we then give a convenient name to it with `using`.

template <size_t n>
struct X {
    type_from_size<n> t;
    // ^ use the template
};

如果您需要支持两个以上的值,则可以像conditional链一样更改多个if/else if/else,但OH MY EYES

template <size_t n>
using type_from_size =
    typename std::conditional<(n <= 0xff), uint8_t,
        typename std::conditional<(n <= 0xffff), uint16_t,
            typename std::conditional<(n <= 0xffffffff), uint32_t,
                uint64_t
            >::type
        >::type
    >::type;

您还可以将专业化与std::enable_if(SFINAE)结合使用,以使其更多&#34;低级别&#34;:

template <size_t n, typename = void>
struct type_from_size_impl;
// Declare a "size_t -> type" function.
//  - the `size_t n` is the input
//  - the `typename = void` is a placeholder
//    allowing us to insert the `std::enable_if` condition.

template <size_t n>
struct type_from_size_impl<n, typename std::enable_if<(n <= 0xff)>::type> {
    using type = uint8_t;
};
// We add a partial specialization
//  - in `std::enable_if<c>::type`, if `c` is true, `::type` will be typedef'ed to `void`
//  - otherwise, `::type` will not be defined.
//  - if `::type` is not defined, substitution failed,
//    meaning we will not select this specialization

template <size_t n>
struct type_from_size_impl<n, typename std::enable_if<(n > 0xff && n <= 0xffff)>::type> {
    using type = uint16_t;
};

template <size_t n>
struct type_from_size_impl<n, typename std::enable_if<(n > 0xffff && n <= 0xffffffff)>::type> {
    using type = uint32_t;
};

template <size_t n>
struct type_from_size_impl<n, typename std::enable_if<(n > 0xffffffff)>::type> {
    using type = uint64_t;
};

template <size_t n>
using type_from_size = typename type_from_size_impl<n>::type;
// Here we want to find a specialization of `type_from_size_impl<n>`
// All 4 specializations will be tried.
// If only one specialization works, we will use that one
// (Which is why we need to ensure the ranges are not overlapping
//  otherwise the compiler will complain)
// Then we take the `::type` out the complete this "type-level function".

答案 1 :(得分:5)

让我们过度杀戮。从选择器开始:

template <int I> struct choice : choice<I + 1> { };
template <> struct choice<10> { };

struct otherwise { otherwise(...) { } };

然后创建一系列返回类型的重载。该选择确保首先选择最小类型,而不必为所有中间整数类型写入双边范围:

template <class T> struct tag { using type = T; }
template <size_t N> using size_t_ = std::integral_constant<size_t, N>;

template <size_t N, class = std::enable_if_t<(N < (1ULL << 8))>>
constexpr tag<uint8_t> tag_from_size(size_t_<N>, choice<0> ) { return {}; }

template <size_t N, class = std::enable_if_t<(N < (1ULL << 16))>>
constexpr tag<uint16_t> tag_from_size(size_t_<N>, choice<1> ) { return {}; 

template <size_t N, class = std::enable_if_t<(N < (1ULL << 32))>>
constexpr tag<uint32_t> tag_from_size(size_t_<N>, choice<2> ) { return {}; }

template <size_t N>
constexpr tag<uint64_t> tag_from_size(size_t_<N>, otherwise) { return {}; }

然后你可以写出发送的顶级:

template <size_t N>
using type_from_size_t = typename decltype(tag_from_size(size_t_<N>{}, choice<0>{}))::type;

并使用它:

template <size_t N>
class X {
    type_from_size_t<N> t;
};

答案 2 :(得分:5)

当然。这是一种更灵活的方式,您可以根据需要添加任意数量的范围,只要它们不重叠即可。

template <std::size_t N, class = void>
struct TypeForSize_;

template <std::size_t N>
struct TypeForSize_<N, std::enable_if_t<
    (N <= 255)
>> { using type = std::uint8_t; };

template <std::size_t N>
struct TypeForSize_<N, std::enable_if_t<
    (N > 255 && N <= 65535)
>> { using type = std::uint16_t; };

template <std::size_t N>
using TypeForSize = typename TypeForSize_<N>::type;

使用未定义类型的大小将导致编译时错误。

答案 3 :(得分:3)

首先写static_if<bool>( A, B )

接下来,写下template<class T> struct tag_type{using type=T;};和支持代码。

template<size_t n>
constexpr auto type_from_size() {
  return static_if< (n<256) >( 
    tag<std::uint8_t>,
    tag<std::uint16_t>
  );
}

现在根据n的值返回不同的标记类型。

使用:

template<size_t n>
class X {
  typename decltype(type_from_size<n>())::type t;
}

或写一个快速别名:

template<size_t n> type_from_size_t = typename decltype(type_from_size<n>())::type;

以下是tag_typestatic_if的代码:

template<class T>struct tag_type{using type=T;};
template<class T>constexpr tag_type<T> tag{};

template<bool b>using bool_t=std::integral_constant<bool, b>;

template<class T, class F>
constexpr T static_if( bool_t<true>, T t, F f ) {
  return t;
}
template<class T, class F>
constexpr F static_if( bool_t<false>, T t, F f ) {
  return f;
}
template<bool b, class T, class F>
constexpr auto static_if( T t, F f ) {
  return static_if( bool_t<b>, t, f );
}
template<bool b, class T>
constexpr auto static_if( T t ) {
  return static_if<b>( t, [](auto&&...){} );
}

并完成。

注意我们也可以static_case。 :)