Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to avoid static_cast when using std::make_tuple with overloaded functions

Tags:

c++

c++11

tuples

g++ says

error: too many arguments to function 'constexpr std::tuple

if I leave out the static_cast in the std::make_tuple call

#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;
}

Here is full error message:

$ 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.

If I change the main function to

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

the program compiles just fine. Is it possible to leave out the static_cast somehow? It seems unnecessary to provide the type func_t two times.

like image 239
Erik Sjölund Avatar asked Jan 11 '13 10:01

Erik Sjölund


1 Answers

Don't use std::make_tuple. Use braced-init-list as:

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

Now the compiler will select the appropriate overload matching func_t.

See live demo

like image 73
Nawaz Avatar answered Oct 28 '22 11:10

Nawaz