c++如何在无法进行类型演绎时调用模板化构造函数

C++ how to call templated constructor when type deduction impossible

本文关键字:调用 演绎 构造函数 类型 c++      更新时间:2023-10-16

编译这段代码没有问题:

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>());
}

这通过利用类型演绎来"欺骗"。

这是非常不正统的,所以可能有更好的方法来做你需要的。