如何使用类型名称? [英] How to use a type of typename?

查看:53
本文介绍了如何使用类型名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++ 11的新手,正在尝试编写一个能够处理动态类型的函数。

I'm new to C++11 and trying to write a function able to handle dynamic types.

#include <functional>
#include <stdio.h>

template <typename T>
struct scase {
  T param;
  std::function<void(T &&)> pc;
  // typedef T type;
  // or
  // using type = T;
  // ?
};

template <size_t I, typename... T>
void docase(std::tuple<T...> &t) {
  auto sc = std::get<I>(t);

  // using casetype = typename std::tuple_element<I, std::tuple<T...>>::type;
  // typename casetype::type ti;
  // ti = sc.param;
  // sc.pc(ti);
}

template <typename... T>
void select(T &&... cases) {
  auto tuple = std::forward_as_tuple(cases...);
  docase<0>(tuple);
}

int main() {
   select(
     scase<int>{123, [](int &&v) {
       printf("%d\n", v);
     }}
   )
   return 0;
}

注释的代码会导致编译器错误。

The commented codes cause compiler errors. What's the correct syntax for this?

编辑:

错误如下:

error C2825: 'casetype': must be a class or namespace when followed by '::'
error C2510: 'casetype': left of '::' must be a class/struct/union
error C2065: 'type': undeclared identifier
error C2146: syntax error: missing ';' before identifier 'ti'
error C2065: 'ti': undeclared identifier


推荐答案

除了示例中的语法错误:

Apart from the syntax errors in your example:

casetype 是引用,因此,您不能使用 :: 运算符。

casetype is a reference, thus, you cant use the :: operator on it.

将行更改为

using casetype = typename std::remove_reference<typename std::tuple_element<I, std::tuple<T...>>::type>::type;

以便删除引用。

实时代码此处

需要将 sc.pc()更改为 sc.pc(std :: move(ti)),因为您的

Also you need to change sc.pc() to sc.pc(std::move(ti)), since your function expects an rvalue reference.

对于第一个注释块:声明成员typedef的两种方法都是有效的,尽管我个人更喜欢使用type = T

For the first comment block: Both ways to declare the member typedef are valid, though I personally prefer using type = T.

这篇关于如何使用类型名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆