在C++ 17中,我们可以做类似的事情
std::pair p = {1,3}; // compiler deduces template parameters to pair<int,int>
Run Code Online (Sandbox Code Playgroud)
从cppreference的文档中我了解到以下内容不起作用:
template<class T1, class T2>
void bar(std::pair<T1,T2>)
{}
void foo()
{
bar({1,3}); // No deduction of pair template arguments
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以证实这一点,并给出一些见解,为什么这不起作用?从技术上讲这应该有效,对吧?有没有讨论过这项工作,还是有点疏忽?
亲爱的程序员小伙伴们,
下面的代码让我有些头疼。它尝试将“通用”对象(=可以从任何东西构造的对象)添加到元组,然后复制该元组。
#include <tuple>
#include <iostream>
#include <typeinfo>
struct anything
{
anything()
{}
anything(const anything&)
{
std::cout << "Called copy c'tor" << std::endl;
}
template<class T>
anything(T arg)
{
std::cout << "Called c'tor with with argument of type " << typeid(arg).name() << std::endl;
// new T(arg); // causes stack overflow
}
};
int main()
{
std::tuple<anything> t;
//
std::cout << "Copy constructing t2, expecting copy c'tor to be called." << std::endl;
std::tuple<anything> t2(t);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
使用 VS 2015 Update …