带有模板参数推导的构造函数执行意外

时间:2019-04-01 18:20:35

标签: c++ templates constructor

问题

被调用的构造函数(即A::A(T))未按预期执行。调用它可以编译(使用GCC-8.3.0),但似乎不执行std::cout operator<<。为什么会这样?

代码

struct A {

    template <typename T>
    constexpr A(T) {
        std::cout << "A::A(T)";
    }
};

struct B {};

int main() {
    ::A a (B());
}

您为什么还要这么做?

我正在尝试通过模板参数推导推断类型T。该对象无关紧要,因此未命名。我需要类型T才能在编译时访问某些数据(static_assert还有其他事项)。据我所知,在C ++中,不可能明确指定 template参数作为构造函数参数。 (因此:A a = A::A<T>)。我可以通过间接的方式来执行此操作,即创建一个用于创建的静态成员函数,可以在其中指定参数:

struct C {
    template <typename T>
    static constexpr C create() { 
        // do whatever you want with T
        return C(); 
    }
};

但是,我主要只是在做实验。

1 个答案:

答案 0 :(得分:2)

您遇到过most vexing parse。您应该改为这样定义@GET @Path("subGroup") @Produces("application/json") @Consumes(MediaType.APPLICATION_JSON) public Response definedSubGrupo(@QueryParam("Us") int US, JSONArray data) { String Data=UtilClass.definedSubGrupo(data); return UtilClass.getReturn(Data); }

a