ltb*_*167 -1 c++ variadic-functions variadic-templates c++11
我知道关于这个话题已经有很多问题,但到目前为止,我没有找到令人满意地回答以下问题的回答.给出以下代码.
#include <map>
template<typename T, typename K>
std::map<T, K> map()
{
return std::map<T, K>();
}
template<typename T, typename...K>
std::map<T, decltype(map<K...>())> map()
{
return std::map<T, decltype(map<K...>())>();
}
int main(int argc, char **argv)
{
std::map<int, int> m2 = map<int, int>();
std::map<int, std::map<int, int>> m3 = map<int, int, int>();
std::map<int, std::map<int, std::map<int, int>>> m4 = map<int, int, int, int>(); // <- Compile Error here
return 0;
}
Run Code Online (Sandbox Code Playgroud)
打电话给
map<int, int, int>()
Run Code Online (Sandbox Code Playgroud)
应归还一个物体
std::map<int, std::map<int, int>>
Run Code Online (Sandbox Code Playgroud)
这适用于最多三个模板参数.如代码中所述,调用具有四个模板参数的pair函数失败,g ++(5.1.0)返回以下错误.
main.cpp: In function 'int main(int, char**)':
main.cpp:20:84: error: no matching function for call to 'map()'
std::map<int, std::map<int, std::map<int, int>>> m4 = map<int, int, int, int>(); // <- Compile Error here
^
main.cpp:4:20: note: candidate: template<class T, class K> std::map<T, K> map()
std::map<T, K> map()
^
main.cpp:4:20: note: template argument deduction/substitution failed:
main.cpp:20:84: error: wrong number of template arguments (4, should be 2)
std::map<int, std::map<int, std::map<int, int>>> m4 = map<int, int, int, int>(); // <- Compile Error here
^
main.cpp:10:40: note: candidate: template<class T, class ... K> std::map<T, decltype (map<K ...>())> map()
std::map<T, decltype(map<K...>())> map()
^
main.cpp:10:40: note: template argument deduction/substitution failed:
main.cpp: In substitution of 'template<class T, class ... K> std::map<T, decltype (map<K ...>())> map() [with T = int; K = {int, int, int}]':
main.cpp:20:84: required from here
main.cpp:10:35: error: no matching function for call to 'map()'
std::map<T, decltype(map<K...>())> map()
^
main.cpp:4:20: note: candidate: template<class T, class K> std::map<T, K> map()
std::map<T, K> map()
^
main.cpp:4:20: note: template argument deduction/substitution failed:
main.cpp:10:35: error: wrong number of template arguments (3, should be 2)
std::map<T, decltype(map<K...>())> map()
^
Run Code Online (Sandbox Code Playgroud)
因此我的问题是:
使用类型操作类型通常更容易.
template<class K0, class K1, class...Ks>
struct my_map;
template<class K0, class K1, class...Ks>
using my_map_t = typename my_map<K0,K1,Ks...>::type;
template<class K0, class K1>
struct my_map<K0,K1>{using type=std::map<K0, K1>;};
template<class K0, class K1, class K2, class...Ks>
struct my_map<K0, K1, K2, Ks...>{
using type=std::map<K0, my_map_t<K1, K2, Ks...>>;
};
Run Code Online (Sandbox Code Playgroud)
做你想要的.
如果你真的想要它作为一个功能:
template<class K0, class K1, class...Ks>
my_map_t<K0, K1, Ks...> map() { return {}; }
Run Code Online (Sandbox Code Playgroud)
诀窍.
函数在其自己的声明中不在上下文中,因此您的map重载不能将其自身视为map其自身返回类型的有效候选.
您可以通过ADL(它自己的声明的上下文,以及函数调用时的ADL,被认为是查找重载)来解决这个问题,但不需要它.
| 归档时间: |
|
| 查看次数: |
314 次 |
| 最近记录: |