我最近接触过这个问题,答案可以概括为"这是一个非受限的背景".
具体来说,第一个说它是这样的东西,然后重定向到"细节"的标准,而第二个引用标准,这至少可以说是神秘的.
有人可以向凡人解释,比如我自己,什么是非受限的背景,什么时候发生,为什么会发生?
c++ templates template-argument-deduction argument-deduction
这段代码有什么问题?
#include <map>
template<typename T>
struct TMap
{
typedef std::map<T, T> Type;
};
template<typename T>
T test(typename TMap <T>::Type &tmap_) { return 0.0; }
int _tmain(int argc, _TCHAR* argv[])
{
TMap<double>::Type tmap;
tmap[1.1] = 5.2;
double d = test(tmap); //Error: could not deduce template argument for T
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个is_iterator<T>类型特征.凡当T是一个迭代器类型is_iterator<T>::value == true,否则是is_iterator<T>::value == false.
到目前为止我尝试了什么:
template <class, class Enable = void>
struct is_iterator : std::false_type {};
template <typename T>
struct is_iterator<T, typename std::enable_if<std::is_pointer<typename
std::iterator_traits<T>::pointer>::value>::type> : std::true_type {};
Run Code Online (Sandbox Code Playgroud)
问:是否有更合适的方式来定义is_iterator类型特征而不是上面显示的类型特征?
我很感激帮助弄清楚我的代码中出现的问题是什么,我已经简化为以下内容:
typedef unsigned short ushort;
template<typename T = ushort*>
struct Foo
{
};
// Specialization -- works when not a specialization
template<
template<typename,typename> class Container ,
template<typename , template<typename,typename> class> class MetaFunction
>
struct Foo<Container<ushort,typename MetaFunction<ushort,Container>::Type> >
{
//typedef Container<ushort,typename MetaFunction<ushort,Container>::Type> TestType; // OK
};
int main()
{
}
Run Code Online (Sandbox Code Playgroud)
在编译(gcc 5.4.0)时,我收到错误:
Test.cpp:14:8: error: template parameters not deducible in partial specialization:
struct Foo<Container<ushort,typename MetaFunction<ushort,Container>::Type> >
^
Test.cpp:14:8: note: ‘template<class, template<class, class> class<template-parameter-2-2> > class MetaFunction’
Run Code Online (Sandbox Code Playgroud)
奇怪的是,Container<ushort,typename MetaFunction<ushort,Container>::Type>专业化的论点似乎是有效的.
为什么这在C++中不起作用?
为什么我不能限制这样foo的参数std::vector<T>::iterator,什么是最好的解决方法?
#include <vector>
template<class T>
void foo(typename std::vector<T>::iterator) { }
int main()
{
std::vector<int> v;
foo(v.end());
}
Run Code Online (Sandbox Code Playgroud)
错误是:
In function ‘int main()’:
error: no matching function for call to ‘foo(std::vector<int>::iterator)’
note: candidate is:
note: template<class T> void foo(typename std::vector<T>::iterator)
note: template argument deduction/substitution failed:
note: couldn’t deduce template parameter ‘T’
Run Code Online (Sandbox Code Playgroud) c++ ×5
templates ×4
c++11 ×1
c++14 ×1
iterator ×1
parameters ×1
template-argument-deduction ×1
type-traits ×1
typedef ×1