c++如何在无法进行类型演绎时调用模板化构造函数
C++ how to call templated constructor when type deduction impossible
编译这段代码没有问题:
struct A
{
template<typename T>
void f(int) {}
};
A a;
a.f<double>(42);
但是,类似的带有模板化构造函数的代码不能编译:
struct A
{
template<typename T>
A(int) {}
};
A a<double>(42);
Gcc在最后一行给出以下错误:错误:'<' token
是否有一种方法使构造函数的例子工作?
无法显式地为构造函数指定模板,因为无法命名构造函数。
根据你想要做的事情,可以使用:
#include <iostream>
#include <typeinfo>
struct A
{
template <typename T>
struct with_type {};
template<typename T>
A(int x, with_type<T>)
{
std::cout << "x: " << x << 'n'
<< "T: " << typeid(T).name() << std::endl;
}
};
int main()
{
A a(42, A::with_type<double>());
}
这通过利用类型演绎来"欺骗"。
这是非常不正统的,所以可能有更好的方法来做你需要的。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在c++类上调用void函数
- 为什么 std::unique 不调用 std::sort?
- 调用专用模板时出错"no matching function for call to [...]"
- 选择要调用的构造函数
- C++为什么尽管我调用了void函数,它却不起作用
- 构造函数正在调用一个使用当前类类型的函数
- 变量没有改变?通过向量的函数调用
- 没有为自己的结构调用列表推回方法
- 使用显式模板参数列表和 [temp.arg.explicit]/3 的函数调用的演绎失败
- 是否可以保证模板模板参数调用用户提供的演绎指南
- 错误:没有匹配的函数调用[…]注意:模板参数演绎/替换失败
- c++如何在无法进行类型演绎时调用模板化构造函数
- 调用模板函数时的模板演绎