c++ - 如何选择构造函数模板?

标签 c++

<分区>

Possible Duplicate:
C++ invoke explicit template constructor

首先假设我有一个带有模板化成员函数的 Data 类:-

class Data
{
public:
    template <class Loader> void load(const std::string& filename);
};

我可以这样用-

Data data;
data.load<SomeLoader>(filename);

一切正常。我可以在编译器时通过模板参数选择我希望我的数据对象使用哪个类来加载一些数据。

但是我不知道如何使用构造函数来做到这一点...

class Data
{
public:
    template <class Loader> Data(const std::string& filename);
};

这似乎编译得很好,但我似乎无法弄清楚如何实际调用该函数。

Data<SomeLoader> data;

那是行不通的,因为那会调用类模板,而不是模板化的构造函数。

我在这里缺少一些语法吗? (如果我添加一个 SomeLoader 类型的构造函数参数,那么编译器会正确地推断出要使用的类,但这不是我需要在这里做的)

最佳答案

您没有遗漏任何语法。不可能明确使用构造函数模板的特化。

标准在 [temp.arg.explicit]/7 中有关于此的注释:

Because the explicit template argument list follows the function template name, and because con- version member function templates and constructor member function templates are called without using a function name, there is no way to provide an explicit template argument list for these function templates.

关于c++ - 如何选择构造函数模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9701525/

相关文章:

c++ - 如何将 Qt 表单类移动到另一个命名空间?

c++ - 如果我在每个平台上使用相同的种子,随机结果会相同吗?

c++ - 为什么我不能用 {std::move(first), std::move(second)} 实例化 std::vector<std::unique_ptr<int>>?

c++ - 库定义位于何处?

c++ - 获取 unicode 代码点的大写或小写(如 uint32_t)

C++ 一行字符串生成器类

c++ - 无法安装 Stanford C++ 库(图形、BasicGraph 类)

c++ - std::wcout 奇怪的错误:std::wstring 的截断输出

c# - 使用 C++/CLI 将图片插入 Excel 并收到 100x 警告 C4691

c++ - 如何在单独的线程中创建多个任务?