【问题标题】:Initializing a variable dependent on type in template parameter in C++在 C++ 中初始化依赖于模板参数中的类型的变量
【发布时间】:2017-07-11 23:11:54
【问题描述】:

我有一个带有静态 const 变量的类,我需要根据模板参数中的变量类型对它进行不同的初始化。有没有办法在没有专业化的情况下做到这一点?

在我的头文件中,我有:

template<class Item>
class CircularQueue {
public:
    static const Item EMPTY_QUEUE;
    ...

尝试在 .cpp 文件中对其进行初始化:

template<typename Item> const Item CircularQueue<Item>::EMPTY_QUEUE = Item("-999");

我希望它初始化为 -999,无论它是 int、double 还是 string。但是,在上面的代码中,我收到“从 'const char' 转换为 'int' 会失去精度 [-fpermissive]”错误。

【问题讨论】:

  • 也许可以创建一个模板化的初始化帮助器来代替它。 template&lt;class T&gt; class Initializer { ... };
  • 不,您需要专业化。您不需要专门化整个 CircularQueue 模板类,但您可以使用单独的专门化帮助器类来初始化 EMPTY_QUEUE

标签: c++ templates constants typename


【解决方案1】:

提供一个使用可以专门化的单独帮助器类的示例,而不必专门化整个模板类,因为您提到您希望看到这种方法的示例。

只需声明一个单独的模板类来设置默认值,并将其专门用于std::string

template<class Item> class defaultItem {

public:

    static constexpr Item default_value() { return -999; }
};

template<> class defaultItem<std::string> {

public:
    static constexpr const char *default_value() { return "-999"; }
};

如果您的 C++ 编译器不是最近的年份,则不必使用 constexpr 关键字。如果需要,您还可以为 const char * 而不是 std::string 定义相同的特化。

然后,您的主类简单地将EMPTY_QUEUE 定义为:

template<typename Item>
const Item CircularQueue<Item>::EMPTY_QUEUE =
           defaultItem<Item>::default_value();

【讨论】:

    猜你喜欢
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    相关资源
    最近更新 更多