使用固定类型生成std :: pair的宏

问题描述 投票:1回答:4

我正在尝试做这样的事情:

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

所以程序员必须编写的内容很简单:

return SOME_PAIR(true, "Amazing");

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

我能做些什么(或与此类似的东西)有效?

编译器:VC110 IDE:VS2012 OS:Win7x64

编辑:以下代码(感谢jxh)使它完美地工作:

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

因此我的lambda函数最终变得非常整洁:

boot.init("log", [&](){
    return INIT_PAIR(log.loaded, "Could not open log config file");
});
c++ macros std-pair
4个回答
2
投票

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

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

0
投票

你忘了吗

#include <utility>

在调用宏的文件中?编译在宏扩展时失败。


0
投票

以下对我有用。

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

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.