c++ - clang 不编译我的代码,但 g++ 可以

标签 c++ templates c++11

谁能帮我处理这段代码:

#include <type_traits>

#include <vector>

struct nonsense { };

template <struct nonsense const* ptr, typename R>
typename std::enable_if<!std::is_void<R>::value, int>::type
fo(void* const)
{
  return 0;
}

template <struct nonsense const* ptr, typename R>
typename std::enable_if<std::is_void<R>::value, int>::type
fo(void* const)
{
  return 1;
}

typedef int (*func_type)(void*);

template <std::size_t O>
void run_me()
{
  static struct nonsense data;

  typedef std::pair<char const* const, func_type> pair_type;

  std::vector<pair_type> v;

  v.push_back(pair_type{ "a", fo<&data, int> });
  v.push_back(pair_type{ "b", fo<&data, void> });
}

int main(int, char*[])
{
  run_me<2>();

  return 0;
}

clang-3.3 不编译这段代码,但 g++-4.8.1 可以,这两个编译器哪个对?我怀疑代码有问题吗?

错误如下:

a.cpp:32:15: error: no matching constructor for initialization of 'pair_type' (aka 'pair<const char *const, func_type>')
  v.push_back(pair_type{ "a", fo<&data, int> });
              ^        ~~~~~~~~~~~~~~~~~~~~~~~
a.cpp:33:15: error: no matching constructor for initialization of 'pair_type' (aka 'pair<const char *const, func_type>')
  v.push_back(pair_type{ "b", fo<&data, void> });
              ^        ~~~~~~~~~~~~~~~~~~~~~~~~

最佳答案

在函数外重定位static struct nonsense data 获取要编译的代码。我不够聪明,无法告诉你原因。

要为 O 参数的不同值自定义 data,可以定义 nonsense 如下......

template <size_t> struct nonsense {
    static nonsense data;
    ⋮
};

……然后使用它……

template <std::size_t O, typename R>
typename std::enable_if<!std::is_void<R>::value, int>::type
fo(void* const)
{
  // Use nonsense<O>::data
}

template <std::size_t O, typename R>
typename std::enable_if<std::is_void<R>::value, int>::type
fo(void* const)
{
  // Use nonsense<O>::data
}

⋮

template <std::size_t O>
void run_me()
{
  std::vector<std::pair<char const* const, func_type>> v;

  v.emplace_back("a", fo<O, int >);
  v.emplace_back("b", fo<O, void>);
}

关于c++ - clang 不编译我的代码,但 g++ 可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17340068/

相关文章:

c++ - 如何使用 Visual Studio 2017 Linux 支持编译和构建 C++17 代码?

c++ - SOL2/C++ - Lua 初学者,是否可以在 Lua 文件之间传递 Lua 表?

c++ - 将 CreateProcess() 的标准输出重定向到管道并在另一个进程中读取它 c++ windows

c++ - 如何从 C++ 中的正则表达式中提取部分?

c++ - std::function 函数与函数指针

c++ - 基本迭代器 C++ 如何迭代 vector 数组

c++ - 基于 SFINAE 的运算符跨命名空间重载

python - 如何在使用 django.test 测试用例时从 View 获取对象

某些类型的模板函数的 C++ 特殊实例,它本身就是模板类

c++ - 局部自动函数变量的销毁与返回值的构造之间的顺序