宏使std::与固定类型配对
Macro to make std::pair with fixed types
我正在尝试这样做:
#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;
}
相关文章:
- 从类型std::函数传递变量失败,尽管调用方期望的类型完全相同
- 错误 C2679:二进制"<<":未找到采用类型 'std::string_view' 的右侧操作数的运算符(或者没有可接受的转换)
- 错误:无法传递非平凡类型"std::string"的对象和更多错误
- 与'operator<<'不匹配(操作数类型'std::ostream {aka std::basic_ostream<char>}'
- std::函数指针错误:无法将 &A::a 转换为类型 std::function<>&&
- 包括<字符串>,使用不完整的类型"std::string"
- 与"operator<<"不匹配(操作数类型'std::ostream'
- 错误:类型"std::__1::basic_string<char>"不提供呼叫运算符
- 错误:请求从"Mstream"转换为非标量类型"std::string {aka std::basic_string<char>}"
- 错误:移动文件时'QString'为非标量类型"std::__cxx11::字符串"
- CLion 无法解析类型 std::unordered_map,即使它提示我包含标头并且编译工作
- 字符串C :libc abi.dylib:终止未被发现的类型std :: out_of_range:basic
- 返回类型 std::optional<std::variant<...>>
- 变量具有不完整的类型std :: String;string.h有很多错误
- 对类型 'A *' 的非常量左值引用不能绑定到不相关的类型 'std::shared_ptr<A>' 的值
- 来自类型为std::basic_string::const_iterator的非常量引用的无效初始化,并且<char>来自类型std::basic_string<char>::
- 类型"std::array<char,6>"和"char"不兼容
- 此错误的含义是什么:从 'char* [40] 转换为非标量类型 'std::string
- 使用 TypedEq() 匹配类型 std::vector<std::vector>
- 如何修复错误:请求从"void"转换为非标量类型"std::vector<int>"