我创建了两个简单的函数来获取模板参数和一个定义类型的空结构:
//S<T>::type results in T&
template <class T>
struct S
{
typedef typename T& type;
};
//Example 1: get one parameter by reference and return it by value
template <class A>
A
temp(typename S<A>::type a1)
{
return a1;
}
//Example 2: get two parameters by reference, perform the sum and return it
template <class A, class B>
B
temp2(typename S<A>::type a1, B a2)//typename struct S<B>::type a2)
{
return a1 + a2;
}
Run Code Online (Sandbox Code Playgroud)
参数类型应用于struct S以获取引用.我用一些整数值调用它们但编译器无法推断出参数:
int main()
{
char c=6;
int …Run Code Online (Sandbox Code Playgroud) 我正在尝试将迭代器作为模板参数传递给模板方法,但编译器抱怨:
error C2783: 'void Test::Assert(std::vector<T>::const_iterator)':
could not deduce template argument for 'T'
Run Code Online (Sandbox Code Playgroud)
产生错误的代码是:
#include "stdafx.h"
#include <iostream>
#include <vector>
class Test
{
public:
template <typename T>
void Assert(typename std::vector<T>::const_iterator it)
{
std::cout << *it << std::endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Test test;
std::vector<double> myVec;
test.Assert(myVec.cbegin());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我猜有一种简单的方法可以使这项工作,因为大多数std算法可以从迭代器中推断出类型.
可能的重复:
非推导上下文的解决方法
GCC 无法推断出这个“简单”函数的参数。有什么办法可以帮助编译器一点吗?
template<int a> struct A
{
template<int b> struct B
{
};
};
template<int a, int b> void test(typename A<a>::template B<b> param) { }
int main()
{
A<1>::B<2> b;
test<1,2>(b); // works
test(b); // doesn't work
}
Run Code Online (Sandbox Code Playgroud)
GCC 4.7.1 的错误消息:
test.cpp: In function 'int main()':
test.cpp:15:8: error: no matching function for call to 'test(A<1>::B<2>&)'
test.cpp:15:8: note: candidate is:
test.cpp:8:29: note: template<int a, int b> void test(typename A<a>::B<b>)
test.cpp:8:29: note: template argument deduction/substitution failed:
test.cpp:15:8: note: couldn't deduce …Run Code Online (Sandbox Code Playgroud)