【问题标题】:how to avoid static_cast when using std::make_tuple with overloaded functions使用带有重载函数的 std::make_tuple 时如何避免 static_cast
【发布时间】:2013-01-11 10:29:24
【问题描述】:

g++ 说

错误:函数 'constexpr std::tuple 的参数太多

如果我在 std::make_tuple 调用中省略了 static_cast

#include <tuple>

typedef int (*func_t)();

int number() {
  return 2;
}

double number(bool a) {
  return 1.2;
}

int main() {
  // With a static_cast it compiles without any error
  // std::tuple<func_t> tup = std::make_tuple(static_cast<func_t>(number));                                                               

  std::tuple<func_t> tup = std::make_tuple(number);
  return 0;
}

这是完整的错误信息:

$ g++ -std=c++11 test.cc
test.cc: In function 'int main()':
test.cc:31:54: error: too many arguments to function 'constexpr std::tuple<typename std::__decay_and_strip<_Elements>::__type ...> std::make_tuple(_Elements&& ...) [with _Elements = {}; typename std::__decay_and_strip<_Elements>::__type = <type error>]'
In file included from test.cc:1:0:
/usr/include/c++/4.7/tuple:844:5: note: declared here
test.cc:31:54: error: conversion from 'std::tuple<>' to non-scalar type 'std::tuple<int (*)()>' requested
$ g++ --version
g++ (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2
Copyright (C) 2012 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

如果我把主函数改成

int main() {
  std::tuple<func_t> tup = std::make_tuple(static_cast<func_t>(number));                                                               
  return 0;
}

程序编译得很好。是否有可能以某种方式省略 static_cast ?似乎没有必要提供两次 func_t 类型。

【问题讨论】:

  • 试试 std::make_tuple()
  • 你怎么看,int number()double number(bool a)应该传递给std::make_tuple(number);什么函数?你可以这样尝试:std::tuple&lt;func_t&gt; tup( (number) );

标签: c++ c++11 tuples


【解决方案1】:

不要使用std::make_tuple。使用 braced-init-list 作为:

std::tuple<func_t> tup { number };

现在编译器将选择与func_t 匹配的适当重载。

live demo

【讨论】:

  • 你能删除“现场演示”链接吗?
  • 这只是测试代码的示例吗?不确定链接的用途。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多