gpt4 book ai didi

c++ - 偏序可变参数模板函数 clang

转载 作者:太空狗 更新时间:2023-10-29 23:15:23 26 4
gpt4 key购买 nike

我目前正在使用 Boost.ProgramOptions 进行一个项目,我必须创建以下结构来为选项添加一些约束:

template <const char *str1, const char*... str2> 
struct restrictedValues
{
...
};

为了验证新选项,您必须重载 boost::program_options::validate 函数:

template<class T, class charT>                                                                            
void validate(boost::any& v, const std::vector< std::basic_string<charT> >& xs, T*, long);

此验证函数的调用如下:

validate(value_store, new_tokens, (T*)0, 0);

正如 boost 所精确:“目标类型是通过一个参数指定的,该参数具有指向所需类型的指针类型。这是没有部分模板排序的编译器的解决方法,就像最后一个 'long/int' 参数一样。”

因此,我按照以下方式编写了我的验证版本:

template<class charT, const char *... str>
void validate(boost::any &v,
const std::vector<std::basic_string<charT> >& values,
restrictedValues<str...>* /*target_type*/,
int /*unused*/) { ... }

看起来我的clang版本(Ubuntu clang version 3.5.0-4ubuntu2~trusty2 (tags/RELEASE_350/final) (based on LLVM 3.5.0))干脆跳过我的版本,在默认版本中优雅地失败。虽然我的 gcc ((Ubuntu 4.8.2-19ubuntu1) 4.8.2) 可以愉快地编译。

编辑 查看一个显示不同行为的实例,感谢@dyp:

Live On Coliru

#include <boost/any.hpp>
#include <vector>
#include <string>
#include <iostream>

template <const char *str1, const char*... str2> struct restrictedValues
{
/*...*/
};

template<class T, class charT>
void validate(boost::any&, const std::vector< std::basic_string<charT> >&, T*, long)
{
std::cout << "default version\n";
}

extern char const client[] = "hello";
extern char const server[] = "world";

template<class charT, const char *... str>
void validate(boost::any &,
const std::vector<std::basic_string<charT> >&,
restrictedValues<str...>* /*target_type*/,
int /*unused*/) {
std::cout << "custom version\n";
}

int main()
{
boost::any a;
std::vector<std::string> xs;
restrictedValues<client, server>* p = 0;
validate(a, xs, p, 0);
}

此外,为结构/函数使用非可变模板(固定数量的 const char*)的相同过程确实很有魅力。

我不太确定是哪个查找过程导致了这样一个模棱两可的错误。如果我的函数没有使用模板,它会根据重载规则进行选择,但事实并非如此。通过阅读模板函数的部分排序规则,两个函数对模板参数具有相同的特化,但我的期望是 int/long 技巧应该起作用。关于如何解开这个模板之谜有什么想法吗?

最佳答案

这里通常的方法是使用强 typedef 使 ADL 工作。

我在一个较旧的答案中对此进行了记录¹:


¹ 第一条评论已经过时,引用了我之前的旧答案。

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

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