Pergunta

I'm trying to do something like this:

#define SOME_PAIR(x, y) std::make_pair<bool, std::string>(x, y)

So that what the programmer has to write is simply:

return SOME_PAIR(true, "Amazing");

But it looks like i'm doing something wrong, as 'no instance of function template "std::make_pair" matches the argument list'.

What can i do to make this (or something similar to this) work?

Compiler: VC110 IDE: VS2012 OS: Win7x64

EDIT: The following code(thanks to jxh) makes it work perfectly:

#define SOME_PAIR(x, y) std::make_pair(bool(x), std::string(y))

And thus my lamda function ends up being really neat:

boot.init("log", [&](){
    return INIT_PAIR(log.loaded, "Could not open log config file");
});
Foi útil?

Solução

You can "cast" the arguments and allow type deduction to instantiate the right template function:

#define SOME_PAIR(x, y) std::make_pair(bool(x), std::string(y))

Outras dicas

Did you forget

#include <utility>

in the file which invokes the macro? The compilation is failing at the point where the macro is expanded.

The following worked for me.

g++ -std=c+0x -Wall -Wextra pair.cpp

#include <iostream>
#include <string>
#include <utility>

#define PAIR(x, y) std::make_pair<bool, std::string>(x, y)

int main(int, char* []) {
  auto p = PAIR(true, "abc");
  std::cout << p.first << " " << p.second << std::endl;
  return 0;
}

Why you don't use templates for it? It will work for most types (not just bool and string). Something like:

#include <iostream>

template<class T1, class T2>
inline std::pair<T1, T2> SOME_PAIR(T1 t1, T2 t2) {
  return std::make_pair(t1, t2);
}

int main() {
  std::pair<bool, std::string> p = SOME_PAIR(true,"hello");

  return 0;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top