为什么C++无法推断模板类型?
Why can't C++ infer the template type?
为什么编译器不能找出这些模板参数?有办法让它这样做吗?
(我使用的是Visual Studio 2010)
template<typename T, typename TFunc>
void call(TFunc func) { func(T()); }
void myfunc(void *) { }
int main() { call(myfunc); }
T
在参数列表中没有出现,因此不能从函数参数中推断出T
。所有要推导的类型必须出现在参数列表中的推导上下文中。例如,
template <typename TReturn, typename TParameter>
void call(TReturn (*f)(TParameter))
{
f(TParameter());
}
函数模板的模板形参推导只能基于函数实参,不能基于其他。函数定义永远不会被用来确定模板参数,所以你的参数T
不可能被推导出来。
您可以通过将类型合并到函数签名中来纠正这种情况:由于您希望外部函数与函数本身一起调用,因此请明确:
template <typename T> void foo(void(*f)(T))
{
T x;
f(x);
// ...
}
如果将函数重载与函子结合使用,一般情况下就不可能确定可以将哪些参数传递给可调用实体。
考虑,例如
struct FunctorExample {
void operator()(int x) {...}
std::string operator()(const std::string& ) {...}
};
如果有某种方法可以诱使编译器在参数上进行模式匹配,那么当应用于FunctorExample
时,它必须具有未定义或错误行为。
相反,趋势似乎是当你想用函子模板元程序时,你指定函子和实参列表。例如boost::result_of
和boost::fusion
。
编辑:也就是说,如果你愿意稍微限制你的注意力,并且你可以使用一些c++ 11语法(decltype
),你可以安排更多的内省:
// Support functors with a very simple operator():
template <typename T> struct argument :
public argument<decltype(&T::operator())> {};
// Pointers to member functions
template <typename C, typename R, typename A> struct argument<R(C::*)(A)>
{typedef A type;};
// Function types
template <typename R, typename A> struct argument<R(A)> {typedef A type;};
// Function pointer types.
template <typename R, typename A> struct argument<R(*)(A)> {typedef A type;};
// Now for call:
template <typename FuncType>
void call(FuncType func) {
typedef typename argument<FuncType>::type Arg;
func(Arg());
}
// example:
class FunctorInt {public: int operator()(int ) {return 0;};};
void myfunc(void *) {}
int main() {
call(myfunc);
call(FunctorInt());
}
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 访问者访问变体并返回不同类型时出错
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 模板元程序查找相似的连续类型名称
- 是否可以从int转换为enum类类型
- 构造函数正在调用一个使用当前类类型的函数
- 我应该使用什么来代替void作为变体中的替代类型之一
- 类中的字符串不命名类型