在我的问题中 类型作为c++中的returntype 我得到了一个答案,给了我这样一个结构。
template <int N>
struct int_type {
using type = std::conditional_t<N <= 8, std::uint8_t,
std::conditional_t<N <= 16, std::uint16_t,
std::conditional_t<N <= 32, std::uint32_t,
std::conditional_t<N <= 64, std::uint64_t,
std::uintmax_t>>>>;
};
这似乎完全符合我的需求,但实践看起来却不一样,因为我无法编译它,因为出现了以下错误。
...Error: expected nested-name-specifier before 'type'
using type = std::conditional_t<N <= 8, std::uint8_t,
^
...Error: using-declaration for non-member at class scope
...Error: expected ';' before '=' token
using type = std::conditional_t<N <= 8, std::uint8_t,
^
...Error: expected unqualified-id before '=' token
我试着在谷歌上搜索,但我找到的所有帖子似乎都没有解决这个具体问题。谁能给我解释一下这段代码的问题?我对C++很陌生
你的代码是完全合法的,只要你的编译器支持 c++14 stdlib的 <type_traits>
定义别名模板的 std::conditional
特质。
然而,错误信息清楚地表明你甚至没有启用 c++11因此 using
根本不作为别名进行解析。要做到这一点,可以添加 -std=c++11
或 -std=c++14
选项到您的配置中。
如果你不能,那么在 c++03 你可以很容易地实现你自己的 conditional
特质。
template <bool B, typename T, typename F>
struct conditional
{
typedef T type;
};
template <typename T, typename F>
struct conditional<false, T, F>
{
typedef F type;
};
template <int N>
struct int_type {
typedef typename conditional<N <= 8, uint8_t,
typename conditional<N <= 16, uint16_t,
typename conditional<N <= 32, uint32_t,
typename conditional<N <= 64, uint64_t,
uintmax_t>::type>::type>::type>::type type;
};
在 c++11 你可以用 std::conditional
而不是 std::conditional_t
唯一不同的是,你需要访问一个嵌套的 typedef type
独自一人,这是一个 属名 (typename
前面的关键词 嵌套名称说明者):
#include <cstdint>
#include <type_traits>
template <int N>
struct int_type {
using type = typename std::conditional<N <= 8, std::uint8_t,
typename std::conditional<N <= 16, std::uint16_t,
typename std::conditional<N <= 32, std::uint32_t,
typename std::conditional<N <= 64, std::uint64_t,
std::uintmax_t>::type>::type>::type>::type;
};
在 c++11 和 c++14你需要包括 <cstdint>
而不是 <stdint.h>
. 前者保证了名字是在 std
命名空间(后者可能只在 全球性 命名空间)。)
为了完整起见,我在这里补充一个答案。
你需要 #include <cstdint>
和 #include <type_traits>
然后用C++14支持编译。代码。
#include <type_traits>
#include <cstdint>
#include <iostream>
template <int N>
struct int_type {
using type = std::conditional_t<N <= 8, std::uint8_t,
std::conditional_t<N <= 16, std::uint16_t,
std::conditional_t<N <= 32, std::uint32_t,
std::conditional_t<N <= 64, std::uint64_t,
std::uintmax_t>>>>;
};
int main()
{
int_type<10>::type t; // std::uint16_t
t = 12;
std::cout << t << std::endl;
}
咦,当你做一个typedef的时候,编译器会告诉你哪里出了问题。这些都是依赖性的类型名,所以你需要在前面加上一个 "类型名",所以这个应该可以。
#include <iostream>
#include <type_traits>
using namespace std;
template <int N>
struct int_type {
using mytype = typename std::conditional<N <= 8, std::uint8_t,
typename std::conditional<N <= 16, std::uint16_t,
typename std::conditional<N <= 32, std::uint32_t,
typename std::conditional<N <= 64, std::uint64_t,
std::uintmax_t
>::type
>::type
>::type
>::type;
};