宏使std::与固定类型配对

Macro to make std::pair with fixed types

本文关键字:类型 std 宏使      更新时间:2023-10-16

我正在尝试这样做:

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

因此,程序员所要写的只是:

return SOME_PAIR(true, "Amazing");

但看起来我做错了什么,因为'没有函数模板"std::make_pair"的实例与参数列表匹配'。

我能做些什么来使这个(或类似的东西)起作用?

编译器:VC110IDE:VS2012操作系统:Win7x64

EDIT:以下代码(感谢jxh)使其完美工作:

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

因此,我的lamda函数最终变得非常简洁:

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

您可以"强制转换"参数并允许类型推导实例化正确的模板函数:

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

你忘了吗

#include <utility>

在调用宏的文件中?在宏展开的地方编译失败。

以下内容对我有效。

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

为什么不使用模板?它适用于大多数类型(不仅仅是bool和string)。类似于:

#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;
}
相关文章: