【问题标题】:how do you call this template constructor? [duplicate]你如何调用这个模板构造函数? [复制]
【发布时间】:2010-07-03 20:40:15
【问题描述】:

可能重复:
C++ invoke explicit template constructor

嗨,

template <typename T>
class testing
{
public:

    template <typename R>
    testing()
    {
       // constructor A
    }

    template <typename R>
    testing(const R&)
    {
       // constructor B
    }
};

调用构造函数A的语法是什么?

我需要在构造函数调用期间传递类型。有没有办法调用它?构造函数 B 是一种解决方法,因为我只需要知道类型而不是整个对象。

谢谢,

斯蒂芬

【问题讨论】:

  • 抱歉重复,因为我不知道该搜索什么。感谢楼下各位的回复。
  • 这就是搜索的问题:当您不知道限定问题的术语时,很难搜索...

标签: c++ templates


【解决方案1】:

您可以创建解决方法:

template<class A>
testing(boost::mpl::identity<A>);

// and instantiate like this
testing(boost::mpl::identity<A>());

我之前问过非常相似的问题 C++ invoke explicit template constructor

【讨论】:

    【解决方案2】:

    你不能。类模板基于T 类型,因此您在实例化类时传递的任何模板参数都将匹配T 而不是R

    编辑:您可能还会发现这篇文章很有用:Constructor templates and explicit instantiation

    您应该继续使用解决方法(构造函数 B)。大多数现代编译器都会优化未使用的参数,因此应该没有区别。

    【讨论】:

    • 是的。无法调用构造函数 A(没有参数的构造函数)。虽然编译器在看到类定义时似乎没有给出警告,但就是没有办法调用它。
    猜你喜欢
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多