终于见到了 c++通过尖括号的模板传递参数的例子了,还是 c++11 中的标准数据结构

2017-07-20 17:22:09 +08:00
 northisland
#include <tuple>
#include <iostream>
#include <string>
#include <stdexcept>
 
std::tuple<double, char, std::string> get_student(int id)
{
    if (id == 0) return std::make_tuple(3.8, 'A', "Lisa Simpson");
    if (id == 1) return std::make_tuple(2.9, 'C', "Milhouse Van Houten");
    if (id == 2) return std::make_tuple(1.7, 'D', "Ralph Wiggum");
    throw std::invalid_argument("id");
}
 
int main()
{
    auto student0 = get_student(0);
    std::cout << "ID: 0, "
              << "GPA: " << std::get<0>(student0) << ", "
              << "grade: " << std::get<1>(student0) << ", "
              << "name: " << std::get<2>(student0) << '\n';
 
    double gpa1;
    char grade1;
    std::string name1;
    std::tie(gpa1, grade1, name1) = get_student(1);
    std::cout << "ID: 1, "
              << "GPA: " << gpa1 << ", "
              << "grade: " << grade1 << ", "
              << "name: " << name1 << '\n';
}

玩的是 c++的元组=_=,参数竟然能通过尖括号来传递=_=

std::get<0>(student0)

template< std::size_t I, class... Types >
typename std::tuple_element<I, tuple<Types...> >::type&
    get( tuple<Types...>& t ) noexcept;

感觉非常酷

3609 次点击
所在节点    分享发现
10 条回复
lrxiao
2017-07-20 21:46:55 +08:00
non-type template parameter

需要编译期常量(而且基本限定为 integer literal )
lrxiao
2017-07-20 21:49:07 +08:00
用 lvalue reference 的做 non-type 的...我是没见过..
codehz
2017-07-20 22:25:49 +08:00
这就觉得酷啦。。你是没看过那些疯狂用模板元编程的。。。
feelapi
2017-07-20 22:31:44 +08:00
github.com/steemit/steem, 看吧,vs2015 编译不过,/Zm2000 都不行。GCC5.2,Debian 下编译通过,boost 用的登峰造极。
northisland
2017-07-21 08:39:53 +08:00
@codehz C++两大疯狂帮派:宏派,模板派
codehz
2017-07-21 13:29:31 +08:00
事实上,对于 C++元组而言,用模板参数传递取的值几乎是唯一正确的做法——毕竟,你要保证类型系统的正常工作,就必须把取值的位置在编译期确定下来。。。
Phoinikas
2017-07-21 20:15:45 +08:00
编译期通过参数取值,有什么比较实用的场景吗
感觉要实用就会陷入模板元编程的深坑。。。
codehz
2017-07-21 21:55:11 +08:00
@Phoinikas 因为 C++是强类型的语言,元祖不同位置的类型可以是不同的。。。所以位置必须是编译期常量,所以就是模板参数咯
很多时候用模板都是为了类型系统的完备性。。。
gnaggnoyil
2017-07-29 16:14:30 +08:00
@Phoinikas C++17 的 structured binding
crazyneo
2017-08-09 18:12:34 +08:00
严格来说,在尖括号里直接写 const_expr 传递参数的做法从 c++98 就可以这么干了,v2ex 里研究过 meta-programming 的估计不在少数—— boost 的影响还是非常巨大的,早点版本的 tr 库几乎都进了 stl。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/376756

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX