gpt4 book ai didi

c++ - 可变参数模板提取

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:39:11 28 4
gpt4 key购买 nike

我遇到了一些我无法理解的事情,也找不到正确解决的方法。我想要实现的目标看起来相对简单:我想比较一些数据。

最好的描述方式是一行代码:

std::tuple<const char *, int, const char *, int> my_data =
std::make_tuple("hello", 13, "world", 37);
// Now I want to compare my_data againt some known value.
assert(Test::entry(my_data, "hello", 13, "world", 37));

为了这个例子,我使用了一个元组。我的情况是,这些数据来自消息对象,并使用 operator>> 提取。但是,这与问题无关。

这里是一个极简代码来说明这个问题。

#include <cstring>
using MyTuple = std::tuple<const char *, int, const char *, int>;

namespace Test
{

// called when we are done
bool extract(MyTuple source)
{
return true;
}

template<typename T,
typename ...Content>
bool extract(MyTuple source, T data, Content... content)
{
if (std::is_same<const char *, T>::value)
assert(0); // why ? :(
std::cout << "Generic: " << data << std::endl;
return extract(source, content...);
}

template<typename ...Content>
bool extract(MyTuple source, const char *str, Content... content)
{
std::cout << "Overloaded: " << str << std::endl;
return extract(source, content...);
}

template<typename ...Content>
bool entry(const std::tuple<const char *, int, const char *, int> &data,
Content... content)
{
return extract(data, content...);
}

};

我通常会在 extract() 函数中执行比较,但为了保持示例简单,我删除了它们。

我想要实现的是适当的调度。根据这个例子,我的理解是调用顺序应该是:

  1. const char * 重载
  2. 一般
  3. 重载const char *
  4. 一般

然而,这个测试程序的输出是:

  1. 重载:你好
  2. 通用:13
  3. 断言失败std::is_same 测试触发了 assert

我发现 const char * 重载在泛型重载被调用一次后不会被调用。

我错过了什么?

编辑:另外,如果我在泛型函数之前定义 const char * 重载,这甚至无法编译。

最佳答案

Also note that if I define the const char * overload before the generic function, this wont even compile.

一个声明就足够了:

template <typename... Content>
bool extract(MyTuple source, const char *str, Content... content); // <- here

template <typename T, typename... Content>
bool extract(MyTuple source, T data, Content... content)
{
std::cout << "Generic: " << data << std::endl;
return extract(source, content...);
}

template <typename... Content>
bool extract(MyTuple source, const char *str, Content... content)
{
std::cout << "Overloaded: " << str << std::endl;
return extract(source, content...);
}

Why?

在没有事先声明的情况下,在此特定名称查找 期间,采用const char* 的重载是不可见的。一些异常(exception)情况可以在 comments below 中找到。 .

关于c++ - 可变参数模板提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27021692/

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